c# - 如何静默绕过对失败(404 Not Found)的 webRequest.GetResponse() 的 REST 调用?
问题描述
当我传递一个可识别的参数时,我的代码可以工作,但是当我传递的参数未被识别时,我会收到一条错误消息。我不一定期望(或需要)在每种情况下都有好的回应,但是当没有结果返回给我时,我不想被异常“打扰”。
我举几个例子。如果我将它传递给 (HttpWebRequest)WebRequest (使用“tt0003854”作为参数):
...我得到了我想要的东西:
{"id":347745,"results":[{"iso_3166_1":"US","release_dates":[{"certification":"","iso_639_1":"","note":"","release_date ":"1936-12-12T00:00:00.000Z","type":3}]}]}
其他尝试也是如此。但是,有些失败,例如当我使用“tt0005929”作为参数时:
...返回:
{"success":false,"status_code":34,"status_message":"找不到您请求的资源。"}
它在这一行失败:
var webResponse = (HttpWebResponse)webRequest.GetResponse();
...然后落入 catch 块,此时我收到一条错误消息,上面写着“远程服务器返回错误:(404)未找到”
如果找不到它是“好的”,但我不希望应用程序因错误消息而停止。我该怎么做才能忽略“404”?
这是我的更多代码,用于上下文:
try
{
var webRequest = (HttpWebRequest)WebRequest.Create(RESTStringToGetMPAARatingForMovieId);
webRequest.Method = "GET"; // <-- GET is the default method/verb, but it's here for clarity
var webResponse = (HttpWebResponse)webRequest.GetResponse();
if (webResponse.StatusCode == HttpStatusCode.NotFound)
{
continue; // this is not reached, even when I get the error
}
if ((webResponse.StatusCode != HttpStatusCode.OK) || (webResponse.ContentLength == 0))
{
continue; // this is not reached, either
}
if ((webResponse.StatusCode == HttpStatusCode.OK) && (webResponse.ContentLength > 0))
{
StreamReader streamReader = new StreamReader(webResponse.GetResponseStream());
string s = streamReader.ReadToEnd();
. . .
}
else
{ // I don't see this message
MessageBox.Show(string.Format("Status code == {0}, Content length == {1}",
webResponse.StatusCode, webResponse.ContentLength));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
解决方案
第一:强制转换或方法调用是否引发错误?(只需将调用拆分并转换为两行)第二:您可以try {...} catch(Exception ex) /*{MessageBox.Show(Ex.Message)*/}
在该行周围放置一个块,但是,您必须确保后面的代码即使使用错误的值也能正常工作,并确保对其进行测试。
推荐阅读
- redis - Socket.io 服务器崩溃时从 Redis 中删除数据
- twilio - 无法获取使用 Twilio 连接功能传递的自定义参数以进行拨出和拨入呼叫
- c++ - Visual Studio 项目中的静态链接 MySQL X DevAPI
- bash - 将空字符串分配给整数会产生零
- python - 如何用最终重定向替换 HTML 中的所有 URL?
- css - 创建剪辑路径波 css 边缘
- if-statement - 我的陈述有问题
- python - manage.py runserver 在生产中经常重新加载
- html - 使用 CSS 将页面缩放为标准字母格式
- django - 如何有效地重用 Django 模型