处理全局异常而不杀死应用程序?

问题描述 投票:2回答:4

我在代码中抛出各种自定义异常。

其中一些是可以恢复的,所以我想要一个全局处理程序来捕获它们,显示警告,然后继续。

我发现AppDomain.UnhandledException事件有一个IsTerminating参数,但这是只读的。

是否有一些事件或其他方式来捕获全局异常,仍然可以让你处理它们并继续?

(这是表格,但我也会对WPF解决方案感兴趣)

c# .net winforms exception-handling global
4个回答
0
投票

你可以使用global.asax和

void Application_Error(object sender, EventArgs e)
{
}

用于捕获未在页面上捕获的错误的事件。

在这个中,你可以使用许多方法,但是这样的方法是这样的:

void Application_Error(object sender, EventArgs e)
{
    Exception opException = Server.GetLastError();

    switch (opException.GetBaseException().GetType().Name)
    {
        case "OptimisticConcurrencyException":
                        //display a friendly message
                    break;
    }


    Server.ClearError();

}

或类似的东西


0
投票

尝试类似的东西:

AppDomain.CurrentDomain.UnhandledException += AppDomainUnhandledException;

public static void AppDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    // You might have to try changing this to your custom exception type and then have overloads or pass it as an object and cast it in the HandleException method
    HandleException(e.ExceptionObject as Exception);
}

private static void HandleException(Exception exception)
{
    if (exception == null) return;

    // Do a check in here against the exceptions that you want to handle or don't want to handle and either display a message, log, quit, etc
}

没有注意到winforms,我没有在很长一段时间内完成表格,所以这是WPF,可能有用或者可能需要调整。


0
投票

找到了解决方案。使用Application.ThreadException而不是AppDomain.UnhandledException。但是你也必须告诉它在UI线程上给出例外:

public static void SetupGlobalExceptionHandler()
{
    Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
    Application.ThreadException += OnException;
}

static void OnException(object sender, ThreadExceptionEventArgs args)
{
    MessageBox.Show("There was a problem. Error is:\n\n" + args.Exception.Message);
}

0
投票

这是一个旧线程,但Dispatcher.UnhandledException事件在其事件参数上有一个Handled参数,可用于阻止应用程序关闭。

protected override void OnStartup(StartupEventArgs e)
{
    Dispatcher.UnhandledException += Dispatcher_UnhandledException;
}
private void Dispatcher_UnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
    HandleException(e.Exception);//your handler
    e.Handled = true;
}
© www.soinside.com 2019 - 2024. All rights reserved.