我们有一个WPF应用程序已经部署到客户端。然而,该应用程序在客户机上随机崩溃,并显示“意外错误”对话框。我们需要能够看到异常消息和最好是堆栈跟踪,但由于它随机崩溃,我们不知道应该在哪里放置try/catch检查以便记录日志。我们正在使用NLog进行日志记录。我的问题是,是否有任何方法可以配置NLog捕获所有未被我们代码处理的异常,或者采用其他方法?
<Application x:Class="WpfTutorialSamples.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
DispatcherUnhandledException="Application_DispatcherUnhandledException"
StartupUri="WPF Application/ExceptionHandlingSample.xaml">
<Application.Resources>
</Application.Resources>
将代码添加到App.xaml文件中,然后将下面的代码添加到App.xaml.cs中
using System;
using System.Windows;
namespace WpfTutorialSamples
{
public partial class App : Application
{
private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
MessageBox.Show("An unhandled exception just occurred: " + e.Exception.Message, "Exception Sample", MessageBoxButton.OK, MessageBoxImage.Error);
e.Handled = true;
}
}}
欲了解更多信息,请阅读WPF中异常处理文章