13.5. Handling Web Server Errors
Problem
You have obtained a response from a web server and you want to make sure that there were no errors in processing the initial request, such as failing to connect, being redirected, timing out, or failing to validate a certificate. You don’t want to have to catch all of the different response codes available.
Solution
Check the
StatusCode
property of the
HttpWebResponse
class to determine what category
of status this StatusCode
falls into, and return
an enumeration value (ResponseCategories
)
representing the category. This technique will allow you to use a
broader approach to dealing with response
codes.
public static ResponseCategories VerifyResponse(HttpWebResponse httpResponse) { // Just in case there are more success codes defined in the future // by HttpStatusCode, we will check here for the "success" ranges // instead of using the HttpStatusCode enum as it overloads some // values int statusCode = (int)httpResponse.StatusCode; if((statusCode >= 100)&& (statusCode <= 199)) { return ResponseCategories.Informational; } else if((statusCode >= 200)&& (statusCode <= 299)) { return ResponseCategories.Success; } else if((statusCode >= 300)&& (statusCode <= 399)) { return ResponseCategories.Redirected; } else if((statusCode >= 400)&& (statusCode <= 499)) { return ResponseCategories.ClientError; } else if((statusCode >= 500)&& (statusCode <= 599)) { return ResponseCategories.ServerError; } return ResponseCategories.Unknown; }
The ResponseCategories ...
Get C# Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.