HttpRequestException vs WebException

user3063281 picture user3063281 · Mar 13, 2014 · Viewed 10.2k times · Source

This is a general question that I'm confused about. I thought once a REST request was made, an error would come back via a WebException. In one case I have I'm getting a HttpRequestException, which doesn't allow me to get the HTTP status code.

I'm new to this stuff, but what is the difference between these? Why are there two types? When does one get used as opposed to another?

WebException seems to work well. HttpRequestException seems like a very weak version of it, where it knows the status code (in it's message) but it won't tell me explicitly what it was.

EDIT: I'm using a HttpClient. Specifically calling client.GetStreamAsync().

Answer

Darrel Miller picture Darrel Miller · Mar 24, 2014

There are three distinct failure scenarios:

a) You could not connect to the server or proxy, in which case a HttpRequestException is thrown. Be aware if your server is down and you are running fiddler, you will never see this exception, you will get a 5XX status code.

b) When reading/writing a network stream, there is some kind of interruption you will get an IOException.

c) You will get back a response with a HttpStatusCode with a 4XX/5XX status code. If your client application chooses to call response.EnsureSuccessStatusCode() then a HttpRequestException will be thrown.

If you decide to call EnsureSuccessStatusCode you are making an explicit decision that you don't care about status codes other than the fact that it was success/fail.

If you really need to bubble up an exception and then later handle the status code then I suggest you create your own extension method to replace EnsureSuccessStatusCode and create your own exception that can store the status code. Or preferably, translate the status code into one of a few different exceptions based on the corrective action you wish to take.