GetResponse抛出WebException,ex.Response为null

wal*_*ter 6 .net c#

我已经找到了如何在GetResponse调用上处理WebException的示例,并解释了如何从WebException Response中提取响应.第二个难题是为什么空响应被视为抛出; 有什么建议吗?

HttpWebResponse response = null;
try
{
    response = (HttpWebResponse) request.GetResponse();
}
catch (WebException ex)
{
    response = (HttpWebResponse)ex.Response;
    if (null == response)
    {
        throw;
    }
}
Run Code Online (Sandbox Code Playgroud)

Bro*_*ass 6

响应永远不应该null- 在这种情况下,作者说WebException这个异常处理程序中无法处理它并且它只是传播了.

这种异常处理仍然不理想 - 您可能想知道发生异常的原因,即:

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;
}
Run Code Online (Sandbox Code Playgroud)