【问题标题】:http client exception handling in asp.net coreasp.net核心中的http客户端异常处理
【发布时间】:2020-12-18 03:34:26
【问题描述】:

我正在使用 .net 5 latest prview..下面是 mvc 中 http 客户端的代码

var response = await _httpClient.SendAsync(request);
         try
        { 
            response.EnsureSuccessStatusCode();
            data = await response.Content.ReadFromJsonAsync<Abc>();
            return data;
        }
        catch (HttpRequestException ex) when (ex.StatusCode = 404)  ----how to check 404 error?
        {
            throw;
        }
        catch (HttpRequestException ex) when (ex.StatusCode == 503)
        {
            throw;
        }

如何在 catch.am 中检查 404 错误或其他详细信息低于错误。在此先感谢...

【问题讨论】:

  • No..i 删除了它也显示另一个错误

标签: c# asp.net-core


【解决方案1】:

最简单的方法是使用适当的枚举进行比较:

var response = await _httpClient.SendAsync(request);
try
{ 
    response.EnsureSuccessStatusCode();
    data = await response.Content.ReadFromJsonAsync<Abc>();
    return data;
}
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.NotFound)  ----how to check 404 error?
{
    throw;
}
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.ServiceUnavailable)
{
    throw;
}

另一种选择是转换为 (int?),但使用枚举应该提供更好的可读性。

【讨论】:

    【解决方案2】:

    HttpRequestException.StatusCodeHttpStatusCode 的类型。不能直接和 int 比较。

    您可以将状态代码转换为 int,例如:

    try
    { 
        response.EnsureSuccessStatusCode();
        data = await response.Content.ReadFromJsonAsync<Abc>();
        return data;
    }
    catch (HttpRequestException ex) when (((int)ex.StatusCode) = 404)
    {
        throw;
    }
    catch (HttpRequestException ex) when (((in)ex.StatusCode) == 503)
    {
        throw;
    }
    

    或者与枚举值比较:

    try
    { 
        response.EnsureSuccessStatusCode();
        data = await response.Content.ReadFromJsonAsync<Abc>();
        return data;
    }
    catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
    {
        throw;
    }
    catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.ServiceUnavailable)
    {
        throw;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-08
      • 1970-01-01
      • 1970-01-01
      • 2021-12-19
      • 1970-01-01
      • 2015-08-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多