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

放肆的年华 提交于 2019-12-13 16:16:23

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/12115030/catch-c-sharp-wpf-unhandled-exception-in-word-add-in-before-microsoft-displays-e

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!