Global exception handler for the MVVM Light application

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.

+6
source share
2 answers

I think now I’ll find out.

The problem is that WPF suppresses the exceptions that occur when binding data to a view, and because my view model is binding data to a DataContext (through a property in my ViewModelLocator using a unit dependency injector), any exceptions in the construction of the view model will be swallowed.

See this SO question for more information.

Therefore, I believe that I just need to make sure that nothing in the constructor should be important for the application to work properly.

+4
source

β€œGlobal” exception handling events for WPF and Windows Forms applications (Application.DispatcherUnhandledException and Application.ThreadException) fire only for exceptions that are thrown on the main user interface thread. You still need to handle workflow exceptions manually.

AppDomain.CurrentDomain.UnhandledException raises any unhandled exception, but does not provide any means to prevent the application from closing after that.

  • You might also want to check out the split and conquer stream merging.
  • Tpl

How to call a method in a user interface thread when using TPL?

+1
source

Source: https://habr.com/ru/post/917094/


All Articles