【发布时间】:2020-04-21 17:09:13
【问题描述】:
我正在尝试处理我的 WPF 应用程序中的所有未捕获异常。
我创建了一个虚拟项目并将 App.xaml.cs 更改为如下所示
public partial class App : Application
{
public App()
{
this.Dispatcher.UnhandledException += (sender, args) =>
{
Console.WriteLine("Test1");
};
AppDomain.CurrentDomain.UnhandledException += (sender, args) =>
{
Console.WriteLine("Test2");
};
Application.Current.DispatcherUnhandledException += (sender, args) =>
{
Console.WriteLine("Test3");
};
AppDomain.CurrentDomain.FirstChanceException += (sender, args) =>
{
Console.WriteLine("Test4");
};
}
}
我还有这个 ViewModel 和名为 TestProp 的属性,我已将其绑定到 XAML 中的 TextBox.Text:
public class TestViewModel
{
private string testProp;
public string TestProp
{
get => testProp;
set
{
testProp = value;
// RAISE EXCEPTION IN PROPERTY SETTER
throw new Exception("Test Exception");
}
}
}
在视图中更改该属性将引发异常,但 App.xaml.cs 中的任何事件都不会被触发,除了 FirstChanceException。
FirstChanceException 的问题是,即使我在代码中处理异常,它也会被引发。
我只是希望全局处理所有未处理的异常,这样我就可以记录错误并显示错误对话框,而不必用 try/catch 包装每个 getter/setter。
这可能吗?谢谢
【问题讨论】:
-
您可以尝试不在构造函数中订阅,而是在 OnStartup() 中订阅吗?
-
@MaciekŚwiszczowski 感谢您的回复。我刚刚尝试过,结果相同 :(。FirstChanceException 是唯一一个命中。
-
是核心还是框架?有哪些版本?我真的很好奇发生了什么 - 我今天一直在测试 UI 线程上的异常处理(.NET Framework),它很有效。
-
.NET 框架。我从一个简单的新项目中尝试了它,以确保我不会发疯,哈哈。如果我在构造函数中抛出该异常 - 或在其他地方设置该属性,它将触发这些事件。只有当我从视图中设置属性时,它似乎没有触发除“FirstChanceException”之外的任何事件。我的调试器将在
throw上停止,但它不会冒泡到 App.xaml.cs 中的事件 -
你能在 Github 上发布你的示例应用吗?
标签: c# wpf mvvm data-binding