处理,记录和显示异常的正确方法

问题描述 投票:0回答:1

这个问题听起来很愚蠢,但是我不熟悉日志记录,显示和处理异常。因为在我进行大量尝试之前(异常异常)来获取异常(测试软件)]

但是现在我正在做一个“真实”软件,它将公开发布。我问的是做这些事情的正确方法。

我正在将WPF与.NET Framework 4.7.2一起使用,并且我也正在使用NLog

目前,我做了一些代码,我只是想像一个评论/建议。我将代码放在启动时,因此在app.xaml.cs中使用受保护的重写OnStartup()

try {

    // Create application main directory
    Directory.CreateDirectory(Reference.AppPath);

} catch (Exception ex) {

    // Log
    Log.Error(ex);

    // The path isn't valid/found (ex: with network name)
    if (ex is DirectoryNotFoundException || ex is IOException || ex is NotSupportedException) {
        MessageBox.Show(string.Format("The application path '{0}' isn't valid..\nPlease check if the path is valid", Reference.AppPath), Reference.AppName, MessageBoxButton.OK, MessageBoxImage.Error);
    }
    // The user hasn't the permission to write (then need to run the application as administrator)
    else if (ex is UnauthorizedAccessException) {
        MessageBox.Show(string.Format("The application hasn't the right to write data in the application path '{0}'..\nPlease start the application as administrator", Reference.AppPath), Reference.AppName, MessageBoxButton.OK, MessageBoxImage.Error);
    }
    // Path is too long (max: 256 chars)
    else if (ex is PathTooLongException) {
        MessageBox.Show(string.Format("The application path '{0}' is too long..\nPlease install the application in another place", Reference.AppPath), Reference.AppName, MessageBoxButton.OK, MessageBoxImage.Error);
    }

    // Shutdown
    Application.Current.Shutdown();

}

我为每个异常都做了一条自定义消息,它有点长

所以我正在等待您的评论/建议,非常感谢,我仍然是那方面的初学者x]

c# wpf nlog
1个回答
0
投票

通常,如果您在程序的主体中有一个大难题,那就是捕获以前未曾处理过的事情,因此,也许可以尝试在更薄的层次上处理异常。您还可以创建像this这样的异常,并在异常本身中定义消息的一部分。

© www.soinside.com 2019 - 2024. All rights reserved.