当我不知道异常可能抛出的位置时,我该如何记录异常?

4
我们有一个WPF应用程序已经部署到客户端。然而,该应用程序在客户机上随机崩溃,并显示“意外错误”对话框。我们需要能够看到异常消息和最好是堆栈跟踪,但由于它随机崩溃,我们不知道应该在哪里放置try/catch检查以便记录日志。我们正在使用NLog进行日志记录。我的问题是,是否有任何方法可以配置NLog捕获所有未被我们代码处理的异常,或者采用其他方法?

2个回答

3
为什么不在整个代码覆盖范围内放置全局try/catch块呢?
由于它是一个WPF应用程序,可能需要进行一些更改。不要让WPF自动打开主窗口,删除App.xaml文件,并从应用程序起始点的代码中通过指定的方式打开窗口(在try/catch中)。
请注意,这不是一个好的做法(就像通常捕获所有异常一样不好),但可能是找到崩溃发生位置的临时解决方法。
编辑:我也邀请您阅读有关WPF中全局try/catch块的相关问题的答案,链接如下:an answer to a related question,其中提供了一些我在撰写答案时不知道的有用内容。

实际上,捕获所有异常是好的,只要你不忽略它们。你需要一个顶层的try/catch块,在关闭之前记录致命异常。 - Steven Sudit

0
<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中异常处理文章


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接