捕获所有异常

3
我有一个项目,可能在任何函数和对象上抛出异常,是否有一种方法可以捕获框架/程序中的所有异常,以便我可以记录它们并稍后查看?我想要调用堆栈和异常消息。我不知道异常将在哪里抛出,但我想记录程序生命周期中发生的任何异常。有没有办法做到这一点?我不想在任何可能抛出异常的函数上进行尝试和捕获。程序会因未处理的异常而中断,但我想先记录它。

这是一个网页、窗体还是其他类型的项目? - Jason
Windows桌面应用程序,具体是WCF。 - iefpw
你的意思是这是一个在Windows Forms应用程序中自托管的WCF服务吗? - John Saunders
6个回答

3

是的,有一种方法可以做到这一点。 在主要代码中编写以下行:

// 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
}

1
一个重要的点是,捕获异常需要根据抛出的异常类型进行适当的处理。如果只有一个大的异常处理程序,你将无法处理个别异常,而且很可能只会忽略它们。但这并不是说不能这样做,或者在所有情况下都不应该这样做。
如果您的项目需要一个大的处理程序,则可以简单地处理AppDomain.UnhandledException事件。即使在其他地方捕获异常,处理此方法也是一个好主意,以确保当您错过异常时,程序不会抛出不友好的错误。这假设您正在创建一个WinForm
由于您还使用了WCF,因此可以查看IErrorHandler接口,以帮助处理故障消息。

1

有没有一种方法可以捕获框架/程序中的所有异常,以便我可以记录它们,以便稍后查看?

捕获所有未处理异常的唯一方法是使用已经提到的 AppDomain.CurrentDomain.UnhandledException,但是你无法使用该事件阻止应用程序终止(好吧,你可以,但我不会告诉你如何,因为它有点hackish)。

然而,大多数框架都有捕获未处理异常的方法,允许你仅仅锁定异常并继续执行。由于你提到了WCF,你可能想阅读关于 IErrorHandler 的内容。

我不想对任何可能抛出异常的函数进行try和catch。

那就是我所做的。不要捕获那个异常。 ;)


0

你可以在应用程序域级别捕获异常 - 应用程序域异常

AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);

如果您阅读链接,它提到一些其他事件可能会导致应用程序域无法触发 - 例如ThreadException - 因此可能需要多个处理程序。

Application.ThreadException += new ThreadExceptionEventHandler (ThreadExceptionHandler);

还要注意以下内容:(与WinForms相关 - SetUnhandledExceptionMode

Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

"Application" 只适用于 WinForms。你可能想要提一下。 - jgauffin

0

你可以随时使用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);
}

0
有没有一种方法可以捕获框架/程序中的所有异常,以便我可以记录它们,以便稍后查看?
是的,对于桌面应用程序或Web应用程序,有处理程序来处理未处理的异常。在桌面应用程序中,事件称为UnhandledException。在Web应用程序中,它是您应用程序入口点(通常是Global.asax.cs)上的Application_Error。
我不想在任何可能引发异常的函数上进行try和catch。程序将因未处理的异常而崩溃,但我想先记录它。
如果您不想捕获异常,您总是可以简单地重新抛出。它将继续向上冒泡,直到导致程序崩溃。
catch(Exception ex)
{
    //logging here
    throw;//rethrow
}

我需要调用堆栈和异常信息。这些都包含在Exception类中。对于事件处理程序,根据应用程序类型有不同的访问方式。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接