There are three different failure scenarios:
a) You could not connect to the server or proxy, in this case the HttpRequestException was thrown. Keep in mind that if your server is turned off and you are using a script, you will never see this exception, you will receive a 5XX status code.
b) There is some kind of interrupt while reading / writing the network stream, you will get an IOException.
c) You will receive a response with an HttpStatusCode with a status code of 4XX / 5XX. If your client application decides to call response.EnsureSuccessStatusCode (), then an HttpRequestException will be thrown.
If you decide to call EnsureSuccessStatusCode, you make the explicit decision that you do not need status codes, other than the fact that it was successful / unsuccessful.
If you really need to throw an exception and then process the status code, I suggest you create your own extension method to replace EnsureSuccessStatusCode and create your own exception that can hold the status code. Or, it is preferable to translate the status code into one of several different exceptions based on the corrective action you want to take.
Darrel miller
source share