What's the usage pattern of HttpResponseMessage.EnsureSuccessStatusCode()
? It disposes of the Content of the message and throws HttpRequestException
, but I fail to see how to programmatically handle it any differently than a generic Exception
. For example, it doesn't include the HttpStatusCode
, which would have been handy.
Is there any way of getting more info out of it? Could anyone show relevant usage pattern of both EnsureSuccessStatusCode()
and HttpRequestException?
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.
This throws an exception just to immediately catch it, which doesn't make any sense. The
IsSuccessStatusCode
property ofHttpResponseMessage
is there for this purpose. Do the following instead.I don't like EnsureSuccessStatusCode as it doesn't return anything meaninful. That is why I've created my own extension:
source code for Microsoft's EnsureSuccessStatusCode can be found here
Synchronous version based on SO link :
What I don't like about IsSuccessStatusCode is that it is not "nicely" reusable. For example you can use library like polly to repeat a request in case of network issue. In that case you need your code to raise exception so that polly or some other library can handle it...