的GetResponse抛出WebException和ex.Response为空 [英] GetResponse throws WebException and ex.Response is null

查看:512
本文介绍了的GetResponse抛出WebException和ex.Response为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经找到例如如何对待WebException上的GetResponse电话,和令人费解的关于如何应对从WebException响应中提取。第二个让人不解的是,为什么空的反应被视为抛出;任何建议?

  HttpWebResponse响应= NULL;
尝试
{
    响应=(HttpWebResponse)request.GetResponse();
}
赶上(WebException前)
{
    响应=(HttpWebResponse)ex.Response;
    如果(空==响应)
    {
        扔;
    }
}
 

解决方案

的反应不应该是 - 在这种情况下,笔者说的 WebException 不能这个异常处理程序中进行处理,它只是传播了。

不过这个异常处理是不理想的 - 你可能想知道的为什么的异常发生,即:

 赶上(WebException前)
{
    如果(ex.Status == WebExceptionStatus.ProtocolError和放大器;&安培;!ex.Response = NULL)
    {
        VAR RESP =(HttpWebResponse)ex.Response;
        如果(resp.Status code ==的HTTPStatus code.NotFound)// HTTP 404
        {
            //文件没找到,考虑处理
            返回false;
        }
    }
    //抛出任何其他异常 - 这应该不会发生
    扔;
}
 

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;
}

这篇关于的GetResponse抛出WebException和ex.Response为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆