【问题标题】:WPF catch all exceptionsWPF 捕获所有异常
【发布时间】:2018-11-01 15:17:19
【问题描述】:

我正在尝试在我的 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 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);
    }

稍后,我会将所有异常写入日志表。

【问题讨论】:

标签: c# wpf


【解决方案1】:

正如@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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-09
    • 1970-01-01
    • 2022-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多