在WPF应用程序中全局捕获异常?

  • A+
所属分类: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);
    }
}

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: