gpt4 book ai didi

c# - GetResponse 抛出 WebException 并且 ex.Response 为空

转载 作者:太空狗 更新时间:2023-10-29 21:35:58 26 4
gpt4 key购买 nike

我找到了如何处理 GetResponse 调用中的 WebException 的示例,并且对如何从 WebException Response 中提取响应感到困惑。第二个疑惑是为什么null response会被当作throw;有什么建议吗?

HttpWebResponse response = null;
try
{
response = (HttpWebResponse) request.GetResponse();
}
catch (WebException ex)
{
response = (HttpWebResponse)ex.Response;
if (null == response)
{
throw;
}
}

最佳答案

响应永远不应为 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;
}

关于c# - GetResponse 抛出 WebException 并且 ex.Response 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7452669/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com