简体   繁体   中英

WPF catch all exceptions

I'm trying to catch all exceptions in my WPF App. I tried the following code but it is not working I don't know why?

<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 ex)
    {
        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);
    }

Later, I will write all exceptions to a log table.

As @Udontknow noted in his comment, not every exception has inner exception(s). Also, there can be, for instance, two inner exceptions. Thus, to correctly collect all exceptions, you can use the following helper GetAllExceptions extension method:

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

Example:

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

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM