Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

http client exception handling in asp.net core

i am using .net 5 latest prview..Below is the code for http client in mvc

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

How to check 404 error or other details in catch.am getting below error.Thanks in advance...

enter image description here

like image 561
Glen Avatar asked Apr 20 '26 05:04

Glen


2 Answers

The easiest way would be to use the proper enum for comparison:

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

Another option would be casting to (int?), but using the enum should provide better readibility.

like image 68
Christoph Sonntag Avatar answered Apr 21 '26 18:04

Christoph Sonntag


HttpRequestException.StatusCode is type of HttpStatusCode. You can't compare directly with int.

You can cast the status code to int like :

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

Or compare with the enumeration's values :

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;
}
like image 33
vernou Avatar answered Apr 21 '26 19:04

vernou



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!