在WPF应用程序中全局捕获异常?
public App()
{
   AppDomain currentDomain = AppDomain.CurrentDomain;
   currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);    
}
static void MyHandler(object sender, UnhandledExceptionEventArgs args)
{
   Exception e = (Exception) args.ExceptionObject;
   Console.WriteLine("MyHandler caught :" + e.Message);
   Console.WriteLine("Runtime terminating: {0}", args.IsTerminating);
}
- 使用nlog的示例代码,该代码将捕获来自AppDomain中所有线程、UI调度程序线程和异步函数的异常:
 - App.xaml.cs:
 
public partial class App : Application
{
    private static Logger _logger = LogManager.GetCurrentClassLogger();
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        SetupExceptionHandling();
    }
    private void SetupExceptionHandling()
    {
        AppDomain.CurrentDomain.UnhandledException += (s, e) =>
            LogUnhandledException((Exception)e.ExceptionObject,"AppDomain.CurrentDomain.UnhandledException");
        DispatcherUnhandledException += (s, e) =>
            LogUnhandledException(e.Exception,"Application.Current.DispatcherUnhandledException");
        TaskScheduler.UnobservedTaskException += (s, e) =>
            LogUnhandledException(e.Exception,"TaskScheduler.UnobservedTaskException");
}
private void LogUnhandledException(Exception exception, string source)
{
    string message = $"Unhandled exception ({source})";
    try
    {
        System.Reflection.AssemblyName assemblyName = System.Reflection.Assembly.GetExecutingAssembly().GetName();
        message = string.Format("Unhandled exception in {0} v{1}", assemblyName.Name, assemblyName.Version);
    }
    catch (Exception ex)
    {
        _logger.Error(ex,"Exception in LogUnhandledException");
    }
    finally
    {
        _logger.Error(exception, message);
    }
}
                版权声明:
                                    
作者:亦灵一梦                                    
链接:https://blog.haokaikai.cn/2021/program/aspnet/wpf/1100.html
                                    
来源:开心博客                                    
文章版权归作者所有,未经允许请勿转载。
                                
                        THE END
                    
                    
                    1
        
                        二维码        
                
                        海报        
        
            
            在WPF应用程序中全局捕获异常?
            
                public App()
{
   AppDomain currentDomain = AppDomain.CurrentDomain;
   currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHan……