简体   繁体   English

如果在 inte.net 断开连接时外部 api 失败,我想捕获异常

[英]I want to catch the exception if external api failed when internet disconnected

private async Task<IEnumerable<Result>> searchresult(string searchText)
{
    try
    {
        rootdata = await HttpClientJsonExtensions.GetFromJsonAsync<Rootdata>(httpClient,$"https://expressentry...");
    }
    catch (WebException ex)
    {
    }

    addresslist = rootdata.d.Results.ToList();

    return addresslist;
}

In this scenario, an unhandled error occurred in the browser and check on inspect shows在这种情况下,浏览器中发生未处理的错误并检查检查显示

Failed to load resource:ERR_INTE.NET_DISCONNECT加载资源失败:ERR_INTE.NET_DISCONNECT

but I want to handle that exception.但我想处理那个例外。

Please help me.请帮我。

Thanks谢谢

because you are trying to catch the error with WebException and ERR_INTE.NET_DISCONNECT is HttpRequestException change WebException to Exception to get all exceptions因为您正在尝试使用WebException捕获错误并且ERR_INTE.NET_DISCONNECT is HttpRequestExceptionWebException更改为Exception以获取所有异常

something like this:是这样的:

private async Task<IEnumerable<Result>> searchresult(string searchText)
{
    var addresslist = new Rootdata();
    try
    {
        rootdata = await HttpClientJsonExtensions.GetFromJsonAsync<Rootdata>(httpClient,$"https://expressentry...");

        addresslist = rootdata.d.Results.ToList();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }

    return addresslist;
}

Aside from using the wrong exception, I feel your pain trying to get an appropriate error message from API faults.除了使用错误的异常之外,我感到您在尝试从 API 故障中获取适当的错误消息时很痛苦。

I use PostAsync and GetAsync instead so I can get an actual HttpResponseMessage back from the request.我改为使用PostAsyncGetAsync ,这样我就可以从请求中获取实际的HttpResponseMessage Now I can check for StatusCodes as well as get access to the content returned by the server.现在我可以检查StatusCodes以及访问服务器返回的内容。

If the server returned content I find that's usually the best API specific error message.如果服务器返回内容,我发现通常是最好的 API 特定错误消息。 The http StatusCodes will be generic and not specific to the API. An exception itself could be anything. http StatusCodes将是通用的,而不特定于 API。异常本身可以是任何东西。 So when I get the error I prioritize;因此,当我收到错误时,我会优先考虑;

  • Response Content响应内容
    • Example: "The API key is invalid. Max lengh 255."示例: “API 密钥无效。最大长度为 255。”
  • Response StatusCodes响应状态码
    • Example: "401: Unauthorized."示例: “401:未经授权。”
  • Exception messages异常信息
    • Example: "Object reference not set to an instance of an object."示例: “对象引用未设置为 object 的实例。”

That might look something like this:这可能看起来像这样:

string error = string.Empty;
HttpResponseMessage response = null;
try
{
    response = await _httpClient.GetAsync("some request");
    if (response.IsSuccessStatusCode)
    {
        // Do work
    }
    else
        error = await HandleError(response);
}
catch (Exception ex)
{
    error = await HandleError(response, ex);
}


private async Task<string> HandleError(HttpResponseMessage response, Exception ex = null)
{
    string error = string.Empty;
    // If the API returned a body, get the message from the body.
    // If you know the content type you could cast to xml/json and grab the error property opposed to all of the content.
    if (response != null && response.Content != null)
        error = $"{response.StatusCode} {response.ReasonPhrase} {await response.Content.ReadAsStringAsync()}";
    else if (response != null && string.IsNullOrEmpty(error))
        error = $"{response.StatusCode} {response.ReasonPhrase}"; // Fallback to response status (401 : Unauthorized).
    else if (ex != null && string.IsNullOrEmpty(error))
        error = ex.Message; // Fall back to exception message.
    else
        return "Unhandled";

    return error;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM