MVVM 中的全局异常处理

luc*_*cas 7 c# wpf mvvm

有没有办法用 MVVM 模式实现全局异常处理。在我现有的情况下,每当 ViewModel 内部发生错误时,应用程序都不会崩溃,只是“隐藏”导致错误的代码之后发生的其余绑定(当然这对最终用户来说是非常误导的,而不是真的,并且永远不应该那样发生)。我不想为 viewModel 中的每个操作都实现 try catch,我不喜欢错误异常的静默方式,我真的很想为 WPF 应用程序实现一种处理全局错误的方法。有没有办法用 MVVM 做到这一点?

luc*_*cas 4

经过长时间的斗争,我终于找到了一种非常简单的方法来实现 ViewModel 内部的异常处理。虽然创建从 DefaultTraceListener 继承的 BindingListener 无疑是在调试模式下查找绑定错误的好方法,但在标准模式下运行解决方案时,这不会捕获 ViewModel 内部发生的异常。但 AppDomain.CurrentDomain.FirstChanceException 会。

应用程序.xaml.cs:

AppDomain.CurrentDomain.FirstChanceException += new EventHandler<System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs>(CurrentDomain_FirstChanceException);


    private void CurrentDomain_FirstChanceException(object sender, FirstChanceExceptionEventArgs e)
    {
            Dispatcher.BeginInvoke(new Action(() => MessageBox.Show("Error Occurred \n\r" + e.Exception.Message + "\n\r" + e.Exception.StackTrace, "ERROR", MessageBoxButton.OK, MessageBoxImage.Error)));
    }
Run Code Online (Sandbox Code Playgroud)