Search code examples
wpfexceptionadd-indispatcherunhandled-exception

Catch C# WPF unhandled exception in Word Add-in before Microsoft displays error message


I am developing a Microsoft Word Add-in using C# and WPF.

In one of my windows, a helper class is throwing an exception in an event. I want the exception to bubble up to the window level so that I can catch it and display an error message to the user. Because it's in an event in the helper class, I can't just surround a method call in the window code with a try/catch block to catch it.

Application.Current returns null so I cannot use the Application Dispatcher.

I can use Dispatcher.CurrentDispatcher.UnhandledException and add a DispatcherUnhandledExceptionEventHandler to it. This works and the exception is caught. However, Microsoft displays the

unhandled exception occurred in your application

error message before my event handler is called.

Am I trying to solve this problem the wrong way or is there a way to suppress Microsoft's unhandled exception error message?


Solution

  • Use UnhandledExceptionFilter to catch the exception before Microsoft Word catches the exception and throws the unhandled exception message.

    Dispatcher.CurrentDispatcher.UnhandledExceptionFilter += 
      new DispatcherUnhandledExceptionFilterEventHandler(Dispatcher_UnhandledExceptionFilter);
    
    void Dispatcher_UnhandledExceptionFilter(object sender, DispatcherUnhandledExceptionFilterEventArgs e)
    {
      e.RequestCatch = false;
      // Display error message or close the window.
    }
    

    Make sure to set RequestCatch to false so that Word does not handle the exception.