嗨,我尝试从这个站点实施解决方案,我的 WPF 应用程序用于全局异常处理。
http://www.codeproject.com/Articles/90866/Unhandled-Exception-Handler-For-WPF-Applications.aspx
我使用 Caliburn Micro 作为 MVVM 框架。我在外部程序集中拥有的服务,它被注入到带有 MEF 的视图模型类中。
这是我在 WPF 应用程序中进行全局异常处理的实现。
应用程序.xaml
DispatcherUnhandledException="Application_DispatcherUnhandledException"
Startup="Application_Startup"
应用类:
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);
}
}
来自外部程序集的服务方法:
public void ServiceLogOn()
{
try
{
}
catch (Exception ex)
{
throw ex;
}
}
此服务方法在视图模型类中调用,例如在按钮单击事件上:
[Export(typeof(ILogOnViewModel))]
public class LogOnViewModel : Screen, ILogOnViewModel
{
public void LogOn()
{
_service.ServiceLogOn();
}
}
我在 Visual Studio 中运行 WPF 应用程序,并在 ServiceLogOn 方法中生成带有消息“错误凭据”的异常。
我希望看到异常的消息框。
但是 Visual Studio 停止调试应用程序并在服务项目的服务方法中显示异常。
所以我尝试从 exe 文件运行 WPF 并在 ServiceLogOn 方法中产生相同的异常。
我收到此错误:
调用的目标已抛出异常。
视图模型类的任何异常都不会在方法中处理:
- Application_DispatcherUnhandledException
- 或 CurrentDomain_UnhandledException。
在 App 类中。
我做什么坏事?
用西蒙福克斯的回答编辑。
我尝试在 Simon Fox 的 MEF 引导程序建议中实施,但我仍然做错了。我将异常的句柄逻辑移动到引导程序类中的 OnUnhandledException 方法。
这是我的引导程序类的代码:
public class MefBootStrapper : Bootstrapper<IShellViewModel>
{
//...
private IMessageBox _msgBox = new MessageBoxes.MessageBoxes();
public bool DoHandle { get; set; }
protected override void OnUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
if (DoHandle)
{
_msgBox.ShowException(e.Exception);
e.Handled = true;
}
else
{
_msgBox.ShowException(e.Exception);
e.Handled = false;
}
}
//...
}
我在按钮上绑定了视图模型中的一些方法并抛出了新的异常。像这样的东西:
public void LogOn()
{
throw new ArgumentException("Bad argument");
}
但是结果是一样的,我从 Visual Studio 中测试了应用程序并得到了这个异常。
调用的目标已抛出异常。