I have found example of how to treat WebException on GetResponse call, and puzzling on how the response can be extracted from WebException Response. The second puzzle is why null response is treated as throw; Any suggestion?
HttpWebResponse response = null;
try
{
response = (HttpWebResponse) request.GetResponse();
}
catch (WebException ex)
{
response = (HttpWebResponse)ex.Response;
if (null == response)
{
throw;
}
}
The response should never be null
- in this case the author is saying the WebException
can't be handled within this exception handler and it is just propagated up.
Still this exception handling is not ideal - you probably want to know why an exception occurred, i.e.:
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null)
{
var resp = (HttpWebResponse)ex.Response;
if (resp.StatusCode == HttpStatusCode.NotFound) // HTTP 404
{
//file not found, consider handled
return false;
}
}
//throw any other exception - this should not occur
throw;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With