【问题标题】:How to handle exception the right way in c# console app如何在 C# 控制台应用程序中以正确的方式处理异常
【发布时间】:2017-11-12 12:14:28
【问题描述】:

我有一个小型控制台应用程序,它将安排在一天中的不同时间间隔,这个控制台应用程序将从 ftp 下载文件。 我有一个名为 BatchProcessor 的类,它从 ftp 下载文件,根据供应商类型将它们解压缩到不同的供应商文件夹中,然后读取并存储到 SQL Server 数据库中。

我需要一些关于我所做的是对还是错的建议,因为我几乎需要在任何阶段捕获异常......

这是代码骨架Program.cs

 class Program
    {
        static void Main(string[] args)
        {
var batchProcessor = new BatchProcessor();
            batchProcessor.Start();
        }
    }

这是 BatchProcessor 类

public class BatchProcessor
{
    public bool Start()
    {
        try
        {
            var result = Connect();
            if (!result) return false;

            result = SearchLatestFiles();
            if (!result) return false;

            result = DownloadFiles();
            if (!result) return false;
        }
        catch (Exception)
        {

            throw;
        }

    }

    public bool Connect()
    {
        try
        {
            // 1. Connect to FTP
        }
        catch (Exception)
        {
            throw;
        }

    }

    public bool SearchLatestFiles()
    {
        try
        {
            // 1. Look for the latest fils
        }
        catch (Exception)
        {

            throw;
        }

    }

    public bool DownloadFiles()
    {
        try
        {
            // 1. Latest files found so download them.
        }
        catch (Exception)
        {

            throw;
        }

    }
}

【问题讨论】:

    标签: .net c#-4.0 exception-handling


    【解决方案1】:

    由于应用程序将在无人值守的情况下运行,因此诊断错误的最佳方法是部署某种日志记录。我建议使用作为 Nuget 包提供的 log4net。它易于安装和配置,在抛出错误之前,您应该记录错误消息和堆栈。 每天查看这些日志的好习惯。 还有一件事:您在课堂上抛出了咳嗽错误,但 main 不处理这些错误 - 这将导致应用程序崩溃和异常终止。

    祝你好运

    【讨论】:

    • 谢谢Yuri,我也是这么想的,但没能做出决定,现在我会听从你的建议。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-02
    • 1970-01-01
    • 1970-01-01
    • 2011-03-09
    • 1970-01-01
    相关资源
    最近更新 更多