1

如何在 Windows 应用程序或 Windows 服务Application_Error中获取一般发生的错误,例如HttpApplication

4

2 回答 2

4

您可以使用以下事件来捕获 Windows 窗体应用程序和 .Net 服务中的异常:

AppDomain.FirstChanceException

只要给定 AppDomain 中出现异常,就会触发此事件,即使稍后处理该事件也是如此。这几乎肯定不是你想要的,但我想我会为了完整起见将它包括在内。

请注意,这是每个 AppDomain 的事件 - 如果您使用多个 AppDomain,那么您需要为每个 AppDomain 处理此事件。如果您只有一个 AppDomain(更有可能),则以下内容将处理此事件:

AppDomain.CurrentDomain.FirstChanceException += CurrentDomain_FirstChanceException;

static void CurrentDomain_FirstChanceException(object sender, FirstChanceExceptionEventArgs e)
{
    throw new NotImplementedException();
}

AppDomain.UnhandledException

只要给定 AppDomain 中存在未处理的异常,就会触发此事件。同样,这是一个每个 AppDomain 事件,并以与事件类似的方式连接起来FirstChanceException

AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    throw new NotImplementedException();
}

您可以在您喜欢的任何时候挂钩这两个事件,但是您可能希望尽快执行此操作,否则在您挂钩事件处理程序之前可能会引发异常。Main类中方法的开始Program通常是执行此操作的好地方。

请注意,在 Windows 窗体应用程序中,此事件可能不会被触发,因为 Windows 窗体应用程序中未处理的异常处理方式不同(由 Windows 窗体基础结构),因此有时不会在 AppDomain 中作为未处理的异常传播.

看看为什么我的 Catch 块只在 Visual Studio 中调试时运行?

Application.ThreadException

(仅适用于 Windows 窗体应用程序)

当在 Windows 窗体应用程序中引发未处理的异常时,会发生这种情况,然后由 Windows 窗体基础结构捕获。您可能应该使用它而不是AppDomain.UnhandledException在 Windows 窗体应用程序中捕获未处理的异常:

Application.ThreadException += Application_ThreadException;

static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
    throw new NotImplementedException();
}

同样,您希望尽快将其连接起来 - 您的Main方法在Program类中的开始通常是执行此操作的好地方。

概括

请注意,它们都不完全Application_ErrorASP.Net 应用程序的方法,但是如果您正在创建 Windows 窗体应用程序,那么您可能想要使用Application.ThreadException,如果您正在创建 Windows 服务,那么您可能想要AppDomain.UnhandledException

于 2011-11-15T13:22:00.030 回答
1

您可以像这样订阅 UnhandledException 事件:

AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;

在您的代码中有一个方法,如下所示:

private void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    // DoSomething
}
于 2011-11-15T13:22:10.897 回答