Search code examples
c#wpfmvvmprismmef

Handling exceptions in Prism 4 modules


I've gone through a number of threads here about this topic with no success. It seems that in the App.xaml.cs of our WPF application, handling DispatcherUnhandledExceptions and AppDomain.CurrentDomain.UnhandledException don't catch everything.

In this specific instance we have 7 prism modules. My exception handling code is below (almost identical for UnhandledException):

private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
    {
        try
        {
            var ex = e.Exception.InnerException ?? e.Exception;
            var logManager = new LogManager();
            logManager.Error(ex);


            if (!EventLog.SourceExists(ex.Source))
                EventLog.CreateEventSource(ex.Source, "AppName");
            EventLog.WriteEntry(ex.Source, ex.InnerException.ToString());

            var emb = new ExceptionMessageBox(ex);
            emb.ShowDialog();
            e.Handled = true;

        }
        catch (Exception)
        { }
    }

The problem seems to be the unhandled exceptions occurring in the modules. They aren't caught by the code above and they cause the application to crash without logging or displaying any sort of message.

Does anyone have experience with this?


Solution

  • This is what we did in our Prism app to catch exceptions (it catches almost everything):

    static class Program
    {
        [STAThread]
        static void Main()
        {
            try
            {
                 App app = new App();
                 app.InitializeComponent();
                 app.Run();
            }
            catch (Exception e)
            {
                 // Log here
                 // Custom error message.
            }
         }
     }
    

    For this to work you have to change your "Startup Object" to be this class. You can do that in the shell's project properties.