HttpRequestException vs WebException

This is a general question that I am confused about. I thought that as soon as a REST request was made, the error would return via WebException . In one case, I get an HttpRequestException that prevents me from getting an HTTP status code.

I'm new to this, but what is the difference between the two? Why are there two types? When will someone get used to another?

WebException seems to work well. HttpRequestException seems like a very weak version, where it knows the status code (there is a message in it), but it will not tell me what it was.

EDIT: I am using HttpClient . In particular, calling client.GetStreamAsync() .

+8
source share
2 answers

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.

+9
source

WebException Class : An exception that occurs when an error occurs while accessing the network through a pluggable protocol.

HttpRequestException Class : The base class for the exceptions thrown by the HttpClient and HttpMessageHandler classes.

I think the internal HttpRequestException may be a WebException, but I'm not sure if it has ever been.


Note. 404, 302 or any other answer other than 200 (OK) is not an exception. These responses are valid HTTP responses.

+1
source

All Articles