代码之家  ›  专栏  ›  技术社区  ›  Eduard Stefanescu

如何在层之间传输异常?

  •  1
  • Eduard Stefanescu  · 技术社区  · 6 年前

    我有一个分为3层的项目。在业务逻辑层中,有两个读写CSV文件的类。在a中 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);
                }
            }
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   d219    6 年前

    错误的描述自然会出现在您调用它的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)来发送该信息。