Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetResponse throws WebException and ex.Response is null

Tags:

c#

.net

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;
    }
}
like image 387
walter Avatar asked Sep 17 '11 05:09

walter


1 Answers

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;
}
like image 98
BrokenGlass Avatar answered Sep 30 '22 17:09

BrokenGlass