开发者

GetResponse throws WebException and ex.Response is null

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 respo开发者_运维问答nse = 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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜