简体   繁体   中英

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

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

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.

I use PostAsync and GetAsync instead so I can get an actual HttpResponseMessage back from the request. Now I can check for StatusCodes as well as get access to the content returned by the server.

If the server returned content I find that's usually the best API specific error message. The http StatusCodes will be generic and not specific to the API. An exception itself could be anything. So when I get the error I prioritize;

  • Response Content
    • Example: "The API key is invalid. Max lengh 255."
  • Response StatusCodes
    • Example: "401: Unauthorized."
  • Exception messages
    • Example: "Object reference not set to an instance of an 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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