使用 http 客户端进行异常处理 - c#

exception handling with http client - c#

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

注意:第二个 catch 块中的 CustomServiceException 只是扩展了异常 class。

        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);
        }

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

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);
}

嗯,它的作用是:

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