Avoid exception in WebRequestObject
I am reading data from a website as follows:
webRequestObj = (HttpWebRequest)WebRequest.Create("http://localhost/503errorPage.php"); theResponse = webRequestObj.GetResponse(); theResponseStream = theResponse.GetResponseStream(); theStreamReader = new StreamReader(theResponseStream); theWholePage = theStreamReader.ReadToEnd();
If I get to a page that has a 503 error, the line:
theResponse = webRequestObj.GetResponse();
throws a WebException:
The remote server returned an error: (503) Server Unavailable.
Is there a way check if the website returns a 503 error instead of wrapping everything up in a try/catch block and waiting for the exception? I am doing many updates per second and would like to avoid the try/catch if possible.
The cost of the try/catch will be miniscule compared to the time it takes to make the network connection. Really, if performance is what you're worried about - quit worrying :)
Now I'll readily admit that it's annoying at a more philosophical level that you can't make a speculative call - a sort of TryGetResponse - but I don't know of a way of doing that. It's possible that one of the async approaches would work, but that ends up potentially changing quite a lot of code.
Btw, make sure you dispose of the response and the stream - if you don't dispose of the response, you'll be limited in terms of how many connections you can make to the same server.