【问题标题】:How to transfer exceptions between layers?如何在层之间传输异常?
【发布时间】:2018-05-16 18:18:19
【问题描述】:

我有一个项目分为 3 层。在业务逻辑层中,有两个读取和写入 CSV 文件的类。在using 语句中,我需要处理IOException,我发现我可以使用 DTO 来做到这一点并将问题描述“发送”到 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);
            }
        }

【问题讨论】:

  • 一个错误会从你调用它的地方冒泡,所以如果你只是想获取有关错误的信息而不是解决它,这将自然地传递层,
  • 感谢您的评论。我想验证路径是否正确,如果不正确,将抛出 IOException,因此我无法创建另一个类来处理它。
  • 我并不是真的在谈论创建另一个类,您将能够在另一个调用它的过程中看到这个过程的错误(它可以在不同的层中)。如果我尝试在答案中解释它可能是最简单的,我猜我可以使用代码格式
  • 是的,这是真的,但我想详细说明每节课的信息。您可以在回答中解释您想说的内容。
  • 您可以更改错误中的内容并仍然将其传递到堆栈中,您还可能有一些错误捕获,例如检查文件路径是否有效,如果没有抛出错误(然后也会通过)

标签: c# exception design-patterns dto using-statement


【解决方案1】:

错误的描述会自然地出现在您从中调用它的 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 层中与您指定的消息一起被捕获。您可能希望通过多种方式捕获/处理错误,但关键是错误将向上传递;您不需要数据传输对象 (DTO) 来发送该信息。

【讨论】:

  • 谢谢!这是我一直在寻找的方法。我编辑了帖子。
猜你喜欢
  • 2011-11-15
  • 2010-09-18
  • 2019-02-16
  • 2016-03-13
  • 1970-01-01
  • 1970-01-01
  • 2010-10-30
  • 2020-09-23
  • 2013-05-27
相关资源
最近更新 更多