如何在层与层之间传递异常?

How to transfer exceptions between layers?

我有一个分为 3 层的项目。在业务逻辑层中,有两个 类 用于读取和写入 CSV 文件。在 using 语句中,我需要处理 IOException 并且我发现我可以使用 DTO 和 "send" 来做到这一点 UI 分层问题描述,但我没有不知道怎么办。你能给我解释一下吗?或者也许是另一种在层之间传输信息的好方法。

写法:

public void WriteCustomers(string filePath, IEnumerable<Customer> customers)
    {
        try
        {
            using (var streamWriter = new StreamWriter(filePath))
            {
                var csvWriter = new CsvWriter(streamWriter);
                csvWriter.Configuration.RegisterClassMap<CustomerMap>();
                csvWriter.WriteRecords(customers);
            }
        }
        catch (IOException)
        {

        }
    }

一种解决方法:

public void WriteCustomers(string filePath, IEnumerable<Customer> customers)
        {
            if (!File.Exists(filePath))
                throw new IOException("The output file path is not valid.");
            using (var streamWriter = new StreamWriter(filePath))
            {
                var csvWriter = new CsvWriter(streamWriter);
                csvWriter.Configuration.RegisterClassMap<CustomerMap>();
                csvWriter.WriteRecords(customers);
            }
        }

错误的描述自然会冒泡到您调用它的 UI 层,因此您可以通过在该层显示消息来捕获和处理错误。下面是一个伪代码示例,可能有助于解释我的意思:

namespace My.UiLayer
{
    public class MyUiClass
    {
        try
        {
            BusinessLogicClass blc = new BusinessLogicClass();
            blc.WriteCustomers(string filePath, IEnumerable<Customer> customers);
        }
        catch (IOException e)
        {
          // Read from 'e' and display description in your UI here
        }
    }
}

请注意,您可能需要更改以上内容以捕获所有带有 Exception 的异常,而不仅仅是上面的 IOException,具体取决于您可能想要显示的内容用户

如果您想要来自不同过程的特定消息 类 那么您可以执行如下操作:

public void WriteCustomers(string filePath, IEnumerable<Customer> customers)
    {
        try
        {
           // Code
        }
        catch (IOException e)
        {
            throw new IOException("Error in write customers", ex);
        }
    }


public void WriteSomethingElse(string filePath, IEnumerable<Something> s)
    {
        try
        {
           // Code
        }
        catch (IOException e)
        {
            throw new IOException("Error in something else", ex);
        }
    }

并且这些将与您指定的消息一起在调用 UI 层中被捕获。您可能希望通过多种方式 capture/handle 错误,但关键是错误会向上传递;您不需要数据传输对象 (DTO) 来发送该信息。