Jamey McElveen
Jamey McElveen

Reputation: 18325

How can I respond to the StatusCode of WebClient before it throws an exception

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?

Upvotes: 3

Views: 571

Answers (1)

Cheeso
Cheeso

Reputation: 192657

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;

Upvotes: 2

Related Questions