在框架级别捕获 WPF 中的异常

2023-12-02

我正在开发一个轻量级 WPF MVVM 框架,并且希望能够捕获未处理的异常,并理想地从中恢复。

暂时忽略所有不这样做的好论据,我遇到以下情况:

如果我在 App.xaml.cs 的 OnStartup 方法中注册 AppDomain.CurrentDomain.UnhandledException 的处理程序,如下所示...

应用程序.xaml.cs:

protected override void OnStartup(StartupEventArgs e)
{
  AppDomain.CurrentDomain.UnhandledException += new
     UnhandledExceptionEventHandler(this.AppDomainUnhandledExceptionHandler); 

  base.OnStartup(e);
}


 void AppDomainUnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs ea)
{
  Exception e = (Exception)ea.ExceptionObject;
  // log exception
}

然后在我的虚拟机之一中引发异常,处理程序将按预期调用。

到目前为止一切都很好,除了我无法使用这种方法进行恢复之外,我所能做的就是记录异常,然后让 CLR 终止应用程序。

我实际上想做的是恢复并将控制权返回给主框架虚拟机。 (再次抛开反对这样做的动机)。

因此,进行一些阅读后,我决定在同一位置为 AppDomain.CurrentDomain.UnhandledException 注册一个事件处理程序,以便代码现在看起来像这样......

protected override void OnStartup(StartupEventArgs e)
{
  AppDomain.CurrentDomain.UnhandledException += 
    new UnhandledExceptionEventHandler(this.AppDomainUnhandledExceptionHandler); 

  this.DispatcherUnhandledException += 
    new DispatcherUnhandledExceptionEventHandler(DispatcherUnhandledExceptionHandler);

  base.OnStartup(e);
}

void AppDomainUnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs ea)
{
  Exception e = (Exception)ea.ExceptionObject;
  // log exception
}

void DispatcherUnhandledExceptionHandler(object sender, DispatcherUnhandledExceptionEventArgs args)
{
  args.Handled = true;
  // implement recovery
}

问题是,一旦我注册了 this.DispatcherUnhandledException 的处理程序,就不会调用任何事件处理程序。因此,注册 DispatcherUnhandledExceptionHandler 会以某种方式停用 AppDomain.CurrentDomain.UnhandledException 的处理程序。

有谁有捕获未处理的虚拟机异常并从中恢复的方法吗?

值得一提的是,框架中没有明确使用线程。


VS 向您显示异常的原因是因为您已将其设置为这样(您明确执行此操作,或者 - 更有可能 - VS 中的默认值将其配置为这样)。您可以通过以下方式控制 Visual Studio 在调试代码中遇到异常时执行的操作:Debug->Exceptions menu.

即使你有一个钩子,你甚至可以让它断裂,这在某些情况下非常方便。

如果您不使用多线程,那么您应该可以使用 DispatcherUnhandledException 事件,因为它会捕获主 UI 线程上未捕获的所有内容。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在框架级别捕获 WPF 中的异常 的相关文章

随机推荐