Global handling exception in WPF app with Caliburn.Micro

Jan 30, 2011 at 5:54 PM
Edited Feb 3, 2011 at 7:18 PM

Hi I try implement solution from this site im my WPF app for global exception handling.

http://www.codeproject.com/Articles/90866/Unhandled-Exception-Handler-For-WPF-Applications.aspx

I use Caliburn Micro as MVVM framework. Service I have in external assembly and it is injected in view model class with MEF.

Here is my implementation for global exception handling in WPF app.

App.xaml

 

       DispatcherUnhandledException="Application_DispatcherUnhandledException"
         Startup="Application_Startup"

 

App class:

 

public partial class App : Application
{
    private IMessageBox _msgBox = new MessageBoxes.MessageBoxes();

    public bool DoHandle { get; set; }

    private void Application_Startup(object sender, StartupEventArgs e)
    {
        AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
    }

    private void Application_DispatcherUnhandledException(object sender,
                           System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
    {
        if (DoHandle)
        {
            _msgBox.ShowException(e.Exception);
             e.Handled = true;
        }
        else
        {
            _msgBox.ShowException(e.Exception);
            e.Handled = false;
        }
    }


    void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        var ex = e.ExceptionObject as Exception;
        _msgBox.ShowException(ex);
    }


}

   [Export(typeof(ILogOnViewModel))]
    public class LogOnViewModel : Screen, ILogOnViewModel
    {
        public void LogOn()
        {
            _service.ServiceLogOn();
        }
    }

Service method from external assembly:

 

    public void ServiceLogOn()
    {
        try
        {

        }
        catch (Exception ex)
        {

            throw ex;
        }
    }

 

This service method is call in view model class for example on button click event:

  1. I run WPF app in Visual Studio and produce exception with message "Bad credentials" in ServiceLogOn method.

    I expect that I see the message box with the exception.

    But Visual Studio stop debuging app and show exception in service method in service project.

  2. So I try run WPF from exe file and produce same exception in ServiceLogOn method.

    I get this error:

    Exception has been throw by target of an invocation.

Any exception from view model class is not handled in methods:

  • Application_DispatcherUnhandledException
  • or CurrentDomain_UnhandledException.

in App class.

What I do bad?