WINUI 全局异常捕捉

发布时间 2023-07-26 11:41:34作者: 盛沧海

因整个解决方案(solution)由多个项目(project)组成,而程序在运行时,在程序入口的app class中添加的UnhandledException事件(Application.UnhandledException)只能捕捉到主程序的异常,

导致不能捕捉到其他类库的异常。通过查找文档与相应资料,了解到可以通过AppDomain.CurrentDomain.FirstChanceException 进行相应的捕捉,其详细代码如下:

 

 /// <summary>
 /// Invoked when the application is launched.
 /// </summary>
 /// <param name="args">Details about the launch request and process.</param>
 protected override void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args)
 {

     OnlyOneApp();
     InitFrame(args);
     //日志初始化
     NlogHelper.Init();
     UnhandledException += App_UnhandledException;
     AppDomain.CurrentDomain.FirstChanceException += CurrentDomain_FirstChanceException;
     dispatcher = DispatcherQueue.GetForCurrentThread();
 }

 static DispatcherQueue dispatcher;
 private void CurrentDomain_FirstChanceException(object sender, System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs e)
 {
     Exception exception = e.Exception;
     if (exception != null)
     {
         NlogHelper.Logger.Error($"未处理异常 \r\n{e.Exception}");
         dispatcher.TryEnqueue(() =>
         {
             MessageHelper.OpenMessageWindow?.Invoke(true, $"程序异常:\r\n{e.Exception}!");
         });
     }
 }

 private void App_UnhandledException(object sender, Microsoft.UI.Xaml.UnhandledExceptionEventArgs e)
 {
     NlogHelper.Logger.Error($"未处理异常    {e.Exception}");
     e.Handled = true;
     MessageHelper.OpenMessageWindow?.Invoke(true, $"程序异常:{e.Exception}!");
 }