WPF捕获所有异常

Dai*_*ges 0 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>
Run Code Online (Sandbox Code Playgroud)

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);
    }
Run Code Online (Sandbox Code Playgroud)

稍后,我将把所有异常写入日志表.

Joh*_*nyL 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

例:

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

输出:

EXCEPTION #1:
Root Error
============
EXCEPTION #2:
Just inner exception
Run Code Online (Sandbox Code Playgroud)