what is the best way to catch errors in a wpf application. I already added the following to my app.xaml.cs:
void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
var stringBuilder = new StringBuilder();
stringBuilder.AppendFormat("{0}\n", e.Exception.Message);
stringBuilder.AppendFormat(
"Exception handled on main UI thread {0}.", e.Dispatcher.Thread.ManagedThreadId);
// attempt to save data
var result = MessageBox.Show(
"Application must exit:\n\n" + 开发者_如何学编程stringBuilder.ToString() + "\n\nSave before exit?",
"app",
MessageBoxButton.YesNo,
MessageBoxImage.Error);
if (result == MessageBoxResult.Yes)
{
MessageBox.Show(e.Exception.InnerException.ToString());
MessageBox.Show(e.Exception.InnerException.Message.ToString());
}
// Return exit code
this.Shutdown(-1);
// Prevent default unhandled exception processing
e.Handled = true;
}
private void Application_Startup(object sender, StartupEventArgs e)
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
}
void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Exception ex = e.ExceptionObject as Exception;
MessageBox.Show(ex.Message, "Uncaught Thread Exception", MessageBoxButton.OK, MessageBoxImage.Error);
}
But I still get occassions where the app crashes and the error is not shown in a messagebox. How do I debug these sorts of errors? The event log of windows doesn't show me any useful information. And off course, the app works fine in IDE, so that's not really helping either.
In IDE you can catch it. Go to
Debug -> Exceptions.
From the dialog, check the thrown check box of Common Language Runtime Exception.
Now, you would be able to catch it from IDE.
HTH
精彩评论