MVVM Light应用程序的全局异常处理程序

Ant*_*ttu 6 wpf exception-handling mvvm-light

我正在尝试在使用MVVM Light Toolkit构建的WPF应用程序中创建一个简单的全局异常处理程序,但我很难让它工作.

问题是视图模型中出现的异常不会被App的UnhandledException处理程序捕获,即使我为Dispatcher和AppDomain注册一个侦听器,如下所示:

private void Application_Startup(object sender, StartupEventArgs e)
{
   AppDomain.CurrentDomain.UnhandledException += DomainUnhandledException;
   DispatcherUnhandledException += App_DispatcherUnhandledException;
}

private void DomainUnhandledException(object sender, UnhandledExceptionEventArgs unhandledExceptionEventArgs)
{
   var exception = unhandledExceptionEventArgs.ExceptionObject as Exception;
   ShowExceptionMessage(exception);
}
private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
   ShowExceptionMessage(e.Exception);
   e.Handled = true;
}
Run Code Online (Sandbox Code Playgroud)

我发现这个博客文章描述了问题点,使用此代码描述的解决方案剪切了视图模型:

// Throw the exception in the UI thread.
App.Current.RootVisual.Dispatcher.BeginInvoke(() => { throw new MyException(); });
Run Code Online (Sandbox Code Playgroud)

但是,我希望所有异常都冒泡到全局异常处理程序,而不仅仅是我自己在VM中抛出的异常处理程序.

所以问题是:在某个地方以某种方式将异常从其他线程重新抛入UI线程吗?

更新:为App的事件处理程序设置添加了更详细的代码.

Ant*_*ttu 6

我想我现在想出来了.

问题是由于WPF抑制了视图数据绑定中抛出的异常,并且因为我的视图模型被数据绑定到视图的DataContext(通过我的ViewModelLocator中的属性利用统一依赖注入器),视图模型构造中的任何异常都将被吞下去

有关详细信息,请参阅此SO问题.

所以我想我必须确保在构造函数中发生应用程序正确运行的能力并不重要.