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

We write REST as a set of services, and we return errors as different StatusCodes.

In our client application, we prefer that our workflow does not require us to search and exceptions to detect an error code.

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

+3
source share
1 answer

No. Design says nothing but 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;
+2
source

Source: https://habr.com/ru/post/1715640/


All Articles