Usage of EnsureSuccessStatusCode and handling of HttpRequestException it throws

The idiomatic usage of EnsureSuccessStatusCode is to concisely verify success of a request, when you don’t want to handle failure cases in any specific way. This is especially useful when you want to quickly prototype a client.

When you decide you want to handle failure cases in a specific way, do not do the following.

var response = await client.GetAsync(...);
try
{
    response.EnsureSuccessStatusCode();
    // Handle success
}
catch (HttpRequestException)
{
    // Handle failure
}

This throws an exception just to immediately catch it, which doesn’t make any sense. The IsSuccessStatusCode property of HttpResponseMessage is there for this purpose. Do the following instead.

var response = await client.GetAsync(...);
if (response.IsSuccessStatusCode)
{
    // Handle success
}
else
{
    // Handle failure
}

Leave a Comment