wpf 捕获全局异常

  App()
  {
      this.Startup += App_Startup;
  }

  private void App_Startup(object sender, StartupEventArgs e)
  {
      this.DispatcherUnhandledException += App_DispatcherUnhandledException;
      AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
      TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
  }

  //主线程未处理异常
  private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
  {
      //HandyControl.Controls.Growl.Error($"应用程序遇到未处理的异常:{e.Exception.Message}");
      e.Handled = true;
  }

  //未处理线程异常(如果主线程未处理异常已经处理,该异常不会触发)
  private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  {
      if (e.ExceptionObject is Exception ex)
      {
          //HandyControl.Controls.Growl.Error($"应用程序遇到未处理的异常:{ex.Message}");
      }
  }

  //未处理的Task内异常
  private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
  {
      //HandyControl.Controls.Growl.Error($"应用程序遇到未处理的异常:{e.Exception.Message}");
  }
posted @ 2024-05-29 11:26  Hey,Coder!  阅读(55)  评论(0编辑  收藏  举报