【问题标题】:exception handling with http client - c# [closed]使用 http 客户端处理异常 - c# [关闭]
【发布时间】:2021-12-19 05:55:49
【问题描述】:

我有以下代码。这已经存在。 catch 的每个块到底在做什么。这是在 ASP.NET Web API 上处理异常的正确方法吗?如果不是,我该如何正确处理异常。

注意:第二个 catch 块中的 CustomServiceException 只是扩展了 Exception 类。

        try
        {
            ... I am calling my exteral API here using HttpClient class
        }
        catch(HttpRequestException ex)
        {
           Logger.Error("my error message", ex.Message);                
        }
        catch(CustomServiceException)
        {
            throw;  
        }                
        catch (Exception ex)
        {
            Logger.Error("my error message",ex);
        }

【问题讨论】:

    标签: c# asp.net-mvc exception asp.net-web-api


    【解决方案1】:

    嗯,它的作用是:

    • 当抛出异常时,它会检查异常是HttpRequestException 还是派生类型。如果这是真的,那么它会记录错误消息并忽略其余的 catch 块。
    • 当异常不是HttpRequestException 或派生类型时,它检查它是否是CustomServiceException 或派生类型。如果这是真的,那么它会重新抛出异常(注意这里使用了throw,它保留了原始异常数据)。
    • 当异常不是 HttpRequestExceptionCustomServiceException(或任何派生类型)时,我们有这个“全局”catch 块,它将捕获任何异常、记录错误消息并继续工作。

    【讨论】:

      【解决方案2】:

      您的代码在概念上是这样做的:

      try
      {
          //... I am calling my exteral API here using HttpClient class
      }
      catch (HttpRequestException ex)
      {
          Logger.Error("my error message", ex.Message);
      }
      catch (Exception ex) when (ex is not CustomServiceException)
      {
          Logger.Error("my error message", ex);
      }
      

      【讨论】:

        猜你喜欢
        • 2014-04-15
        • 2017-04-08
        • 2020-12-18
        • 1970-01-01
        • 2015-08-18
        • 1970-01-01
        • 2019-07-27
        • 2015-04-26
        • 1970-01-01
        相关资源
        最近更新 更多