12

I've hunted around for some definitive documentation on this but haven't had much luck finding any.

For which HTTP Response Status codes will HttpWebRequest.GetResponse() generate a WebException after doing something like a POST?

Specifically, will it generate a WebException for anything other than status 200 OK? Or will it only generate a WebException for say, 400, 404, and 500 (for the sake of argument)?

I want to know since the server I'm communicating with defines anything other than HTTP 200 OK coming back as an error condition. Can I rely on a WebException being generated for anything other than 200?

I've currently written my code to check the return status code every time and ensure it's 200 OK. If it's not, it will take appropriate action—but there's a lot of duplication between that code and the catch block for a WebException that I'm hoping to clean up.

Any relevant links to documentation would be most appreciated.

Michael
  • 8,362
  • 6
  • 61
  • 88
H. Morrow
  • 151
  • 1
  • 5
  • See the following answer to a related questions for a thorough analysis: http://stackoverflow.com/questions/2182544/c-httpwebrequest-getresponse-how-is-statuscode-usage-handled-for-a-non-excepti/2183380#2183380 – Steve Guidi Sep 07 '10 at 16:36

3 Answers3

3

Ended up doing an explicit check after the response & catching and checking WebExceptions; results in some duplicated code but there's no definitive answer on whether a WebException will ALWAYS occur if the status is NOT 200.

H. Morrow
  • 151
  • 1
  • 5
1

I think it will, but it sounds like a risky assumption to make. For one thing, the MSDN docs make it clear that GetResponse will throw exceptions other than just WebException. However, I can say for definite from experience that a "304 Not-Modified" response will be thrown as a WebException.

All this talk is giving off a whiffy Code Smell; don't use exceptions to control the flow of execution. You would be better off handling exceptions appropriately, then explicitly checking the StatusCode property for your allowable values.

batwad
  • 3,588
  • 1
  • 24
  • 38
  • The WebException itself is caught properly and checked - the issue is however is if the getresponse method does not generate a WebException but rather simply lets things proceed under certain circumstances (i.e from everything I've seen unless the server issues HTTP 200 OK - a webexception pops up...but there's nothing definitive about whether that's the case or not in any documentation that I've seen...) – H. Morrow Jun 01 '10 at 18:25
0

The WebException system is seperate system from the HTTP error system. This is mainly because the HTTP errors are returned by the browser or client and the WebException is thrown by the server while building your page. By the time an HTTP error is found the page is sent to the client and you won't know about it.

MrFox
  • 4,852
  • 7
  • 45
  • 81