Displaying exceptions that occur in the ViewModel

Topics: Prism v2 - WPF 3.5
May 13, 2009 at 4:50 AM


I'm currently trying to propagate exceptions that occur in my ViewModel back to the View, and have been reading about all sorts of patterns on the web, but I am looking for a straight forward way of doing this.

So far the best way I can see to do this easily using Prism is to fire an event using the Event Aggregator in the ViewModel and listen for this event in the View code behind.

Is this the best way to handle this situation using Prism or is there an easier was to do this with the ViewModel pattern?



May 13, 2009 at 1:42 PM

<!-- .style1 { margin-left: 40px; } -->

The way I did this was to create a Module that handles exceptions, in it I have all the view/viewmodels for showing exceptions and code to determine the type of exception and how to show it.

This module gets loaded when the application loads and its view injected in the shell inside a popup.

When an exception occurs anywhere in the app, an event is fired, the exception module is setup to listen to the event and handle the exception by showing the popup and graying out the back of the app:


// Subscribe to Application Exceptions Notifications

if (eventAggregator!=null)



I also keep an internal list of exceptions, so that you can see ALL exceptions that have occured in the app, kind of like IE handles errors in the page and shows you all of them. (Of course remember not to save a REFERENCE of the exception, that would be BAD)

It has worked really well, one thing though, if an unhandled exception occurs, and I have to handle it in DispatcherUnhandledException, it will of course not be handled by the exception module. In this 

case I basically have an ExceptionUtility class in my Exception Module that gets call to display the exception, this of course requires that you reference the exception module from your shell, but wouldn't you do it anyway?:


static void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)


e.Handled = true;

          ExceptionUtility.ShowExceptionDialog("Unhandled Error",new ExceptionRecord(e.Exception));


Exception record converts an exception in to a plain text based object for record keeping.

The pros of this are:

- Centralized exception handling

- Same view/viewmodel for ALL exceptions

- Easier exception logging from a single place

- Allows you to keep a history of exceptions the user can navigate.