WPF捕获所有异常

时间:2018-05-22 18:58:43

标签: c# wpf

我正在尝试捕获WPF应用程序中的所有异常。我尝试了以下代码,但它无法正常工作我不知道为什么?

<Application x:Class="DBFilter.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         StartupUri="MainWindow.xaml"
         Exit="Application_Exit"               
         DispatcherUnhandledException ="AppDispatcherUnhandledException"
         >
<Application.Resources>

</Application.Resources>
</Application>

App.xaml.cs

protected override void OnStartup(StartupEventArgs e)
    {
        AppDomain.CurrentDomain.UnhandledException += new 
UnhandledExceptionEventHandler(AppDomainUnhandledExceptionHandler);
        System.Windows.Forms.Application.ThreadException += new 
ThreadExceptionEventHandler(Application_ThreadException);
        Application.Current.DispatcherUnhandledException += new 
DispatcherUnhandledExceptionEventHandler(AppDispatcherUnhandledException);
}

void AppDomainUnhandledExceptionHandler(object sender, 
UnhandledExceptionEventArgs ea)
    {
        Exception ex = (Exception)ea.ExceptionObject;    
 MessageBox.Show(ex.Exception.InnerException.Message);

    }

void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
    {
        MessageBox.Show(e.Exception.InnerException.Message);
    }                       

void AppDispatcherUnhandledException(object 
sender,DispatcherUnhandledExceptionEventArgs e)
    {
        MessageBox.Show(e.Exception.InnerException.Message);
    }

稍后,我会将所有例外写入日志表。

1 个答案:

答案 0 :(得分:5)

正如@Udontknow在他的评论中指出的那样,并非每个例外都有内部异常。此外,例如,可以有两个内部异常。因此,要正确收集所有例外,您可以使用以下帮助GetAllExceptions扩展方法:

public static class ExtensionMethods
{
    public static string GetAllExceptions(this Exception ex)
    {
        int x = 0;
        string pattern = "EXCEPTION #{0}:\r\n{1}";
        string message = String.Format(pattern, ++x, ex.Message);
        Exception inner = ex.InnerException;
        while (inner != null)
        {
            message += "\r\n============\r\n" + String.Format(pattern, ++x, inner.Message);
            inner = inner.InnerException;
        }
        return message;
    }
}

示例:

try
{
    throw new Exception("Root Error", innerException: new Exception("Just inner exception"));
}
catch(Exception ex)
{
    WriteLine(ex.GetAllExceptions());
}

<强>输出:

EXCEPTION #1:
Root Error
============
EXCEPTION #2:
Just inner exception