我找到了如何在GetResponse调用上处理WebException的示例,并解释了如何从WebException Response中提取响应。第二个难题是为什么空响应被视为抛出;有什么建议吗?
HttpWebResponse response = null;
try
{
response = (HttpWebResponse) request.GetResponse();
}
catch (WebException ex)
{
response = (HttpWebResponse)ex.Response;
if (null == response)
{
throw;
}
}
答案 0 :(得分: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;
}