I am trying to create a simple global exception handler in a WPF application that is created using the MVVM Light Toolkit, but it is difficult for me to work with it.
The point is that the exception that occurred in the view model will not fall into the App UnhandledException handler, although I register the listener for both the dispatcher and AppDomain as follows:
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; }
I found this blog post describing a problem that describes a solution with this code shot for view models:
// Throw the exception in the UI thread. App.Current.RootVisual.Dispatcher.BeginInvoke(() => { throw new MyException(); });
However, I would like all the exceptions to turn into a global exception handler, and not just the ones that I throw into the virtual machine.
So, the question arises: is it possible to somehow throw exceptions from other threads into the user interface thread in one place?
Update : Added more detailed code to configure the application event handler.
Anttu source share