我有一个项目,可能在任何函数和对象上抛出异常,是否有一种方法可以捕获框架/程序中的所有异常,以便我可以记录它们并稍后查看?我想要调用堆栈和异常消息。我不知道异常将在哪里抛出,但我想记录程序生命周期中发生的任何异常。有没有办法做到这一点?我不想在任何可能抛出异常的函数上进行尝试和捕获。程序会因未处理的异常而中断,但我想先记录它。
是的,有一种方法可以做到这一点。 在主要代码中编写以下行:
// Add the event handler for handling UI thread exceptions to the event.
Application.ThreadException += new ThreadExceptionEventHandler(MainForm_UIThreadException);
// Set the unhandled exception mode to force all Windows Forms errors to go through
// our handler.
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
// Add the event handler for handling non-UI thread exceptions to the event.
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
然后处理异常情况。
private static void MainForm_UIThreadException(object sender, ThreadExceptionEventArgs t)
{
//do something
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
//do something
}
WinForm
。WCF
,因此可以查看IErrorHandler接口,以帮助处理故障消息。有没有一种方法可以捕获框架/程序中的所有异常,以便我可以记录它们,以便稍后查看?
捕获所有未处理异常的唯一方法是使用已经提到的 AppDomain.CurrentDomain.UnhandledException
,但是你无法使用该事件阻止应用程序终止(好吧,你可以,但我不会告诉你如何,因为它有点hackish)。
然而,大多数框架都有捕获未处理异常的方法,允许你仅仅锁定异常并继续执行。由于你提到了WCF,你可能想阅读关于 IErrorHandler 的内容。
我不想对任何可能抛出异常的函数进行try和catch。
那就是我所做的。不要捕获那个异常。 ;)
你可以在应用程序域级别捕获异常 - 应用程序域异常
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
如果您阅读链接,它提到一些其他事件可能会导致应用程序域无法触发 - 例如ThreadException - 因此可能需要多个处理程序。
Application.ThreadException += new ThreadExceptionEventHandler (ThreadExceptionHandler);
还要注意以下内容:(与WinForms相关 - SetUnhandledExceptionMode)
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
你可以随时使用AppDomain.UnhandledException
static void Main()
{
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(AppDomain_UnhandledException);
}
private static void AppDomain_UnhandledException(object sender, UnhandledExceptionEventArgs args) {
Logger.Log((Exception)args.ExceptionObject);
}
catch(Exception ex)
{
//logging here
throw;//rethrow
}
Exception
类中。对于事件处理程序,根据应用程序类型有不同的访问方式。