tags:

views:

40

answers:

1

We are writing a REST like set of services and we are returning errors as different StatusCodes.

In our client application we we prefer if our work flow did not require us to catch and cast an exception to discover the error code.

Is there a way to tell the WebClient or HttpWebRequest to stop throwing exceptions when it encounters a StatusCode other than 200?

+1  A: 

No. The design says anything other than 200 or 201 is exceptional.

HttpStatusCode httpStatusCode;
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://example.org/resource");
try
{
    using (HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
    {
        // handle 200/201 case
    }
}
catch (WebException webException)
{
    if (webException.Response != null)
    {
        HttpWebResponse httpWebExceptionResponse = (HttpWebResponse)webException.Response;
        switch (httpWebExceptionResponse.StatusCode)
        {
            case 304:  // HttpStatusCode.NotModified
                break;
            case 410:  // HttpStatusCode.Gone
                break;
            case 500:  // HttpStatusCode.InternalServerError
                break;
            // etc
        } 
    }
    else
    {
       //did not contact host. Invalid host name?
    }
}
return httpStatusCode;
Cheeso