HttpException vs. WebException
ran into a tricky problem while coding my Requestor
class within the exyus framework. i use this class to make HTTP calls (using the System.Net.HttpWebRequest
) primarily within my own server space. all is fine until an error occurs. then i got confused.
see, i have been leveraging HttpException
throughout my framework. this helps me focus on the HTTP Status codes as a way to determine how my request has turned out. but, it wasn't working. in fact, every failed request was returned as an HTTP 500 error. my signal that the framework gives up and just throws a server error.
turns out HttpWebRequest
*never* throws HttpException
. instead, it throws WebException
. my code was never catching the error and falling through to the generic exception handler (thus throwing the 500 error). even more annoying, WebException
does not have an HTTP status code at all. that's 'cuz WebResponse (the base of HttpWebReponse) is used for more than just HTTP conversations. so, how am i to retrieve the HTTP Status code? aha - msft, docs has the answer:
The HttpWebRequest class throws a WebException when errors occur while accessing a resource. The WebException.Status property contains a WebExceptionStatus value that indicates the source of the error. When WebException.Status is WebExceptionStatus.ProtocolError, the Response property contains the HttpWebResponse received from the resource.
so... i just need to sniff for the ProtocolError
and, if found, get a copy of the Response
object and *then* get the HTTP Status code. convoluted, but it works. here's what i have now:
// lots of other interesting code up here... catch (WebException wex) { // typical http error if (wex.Status == WebExceptionStatus.ProtocolError) { HttpWebResponse wrsp = (HttpWebResponse)wex.Response; throw new HttpException((int)wrsp.StatusCode, wrsp.StatusDescription); } else { throw new HttpException(500, wex.Message); } } // other interesting code goes down here...