Handle Exception Thrown by Event Aggregator

Topics: Bootstrappers & IoC, Bugs, Framework Services
May 10, 2013 at 10:45 PM

Part of our Bootstrapper calls IWindowManager to show our main window
MainWindowViewModel mainWindowViewModel = IoC.Get<MainWindowViewModel>();

Our Views are in one project, our view models in another project, and our model is in a third project.

During this process we publish a message via eventaggregator
EventAggregator.Publish(new MessageSentFromMainViewModel<ISomeInterfaceBase>(SelectedItem));
We handle this message in another view model like this
 public void Handle(MessageSentFromMainViewModel<ISomeInterfaceBase > message)

the MethodThatisCasuingProblem lives in the model project. That methods throws an exception.

I want to be able to catch this exception and show the user the error message and handle it gracefully. Unfortunately, that exception gets caught in the event aggregator and does not get sent up to either the bootstrapper, or Application, or the Appdomain. I have the following 2 unhandled exception handlers in the App.xaml.cs
private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)

private void ApplicationDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
Also, in our bootstrapper I have
protected override void OnUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
The exception is NOT caught by any of those handlers, is there a way for us to handle this exception globally, since we do not want to go everywhere this method (it is part of our repository and there are many other calls like it and we would like to handle it globally instead of peppering our application with many try/catch)

Any help will be greatly appreciated.
May 12, 2013 at 12:11 PM
Hi BishMan,

We do not explicitly handle exceptions in the EventAggregator as you can see from the fragment below.
foreach(var pair in supportedHandlers) {
                    if(pair.Key.IsAssignableFrom(messageType)) {
                        var result = pair.Value.Invoke(target, new[] { message });
I would have expected OnUnhandledException to fire in this instance. Are you handling Exception anywhere up the chain, this could swallow it.

There is a simple way to do what you which however :
EventAggregator.DefaultPublicationThreadMarshaller = action =>
                    // Ensure all calls are marshaled to UiThread
                    Execute.OnUIThread(() =>
                            catch (Exception) // Make this specific to the one you want.
                                // Handle here.
You can configure this in the bootstrapper.