【问题标题】:Logging unhandled exception independent of user interaction独立于用户交互记录未处理的异常
【发布时间】:2021-06-04 09:56:47
【问题描述】:

我有一个 WPF C# 应用程序,我在其中将未处理的异常记录到文件中。所以在 MainWindow.xaml.cs 我定义了一个事件处理程序如下:

public MainWindow()
{
InitializeComponent();
//...
this.Dispatcher.UnhandledException += OnDispatcherUnhandledException;
}

然后我将异常记录如下:

    void OnDispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
    {                
     myLogger.log(myLogPath, e.Exception.ToString(), e.Exception.StackTrace, Logger.LogLevel.Error);           
    }

而当发生此类异常时,.NET 会弹出以下消息框:

问题是,如果单击继续,然后等待几秒钟,则会记录异常。但是,如果一个人在没有继续的情况下退出消息框,则不会记录异常。

即使用户没有单击继续,我也希望记录异常。是否有解决方法或至少强制消息框自动选择继续?

【问题讨论】:

    标签: c# .net wpf


    【解决方案1】:

    DispatcherUnhandledExceptionEventArgsHandled 属性设置为true,进行日志记录然后退出应用程序:

    void OnDispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
    {
        e.Handled = true;
        myLogger.log(myLogPath, e.Exception.ToString(), e.Exception.StackTrace, Logger.LogLevel.Error);
    
        MessageBox.Show("Error...", "caption...", MessageBoxButton.OK, MessageBoxImage.Error);
        Current.Shutdown();
    }
    

    您还应该显示您的自定义错误消息。一般的 .NET 错误对话框对用户显示不是很有帮助或很好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-11
      • 2013-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多