问题描述
当我传递一个可识别的参数时,我的代码可以工作,但是当我传递的arg无法识别时,我会收到一条错误消息。我不一定在每种情况下都期望(或需要)一个良好的响应,但是当没有结果可返回给我时,我不想因异常而“烦恼”。
我将举几个例子。如果我将此传递给(HttpWebRequest)WebRequest(使用“ tt0003854”作为arg):
...我得到了我想要的东西:
{“ 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”作为arg时:
...返回:
此行失败:
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)*/}
块,但是,必须确保以后的代码即使使用错误的值也可以工作,请确保对其进行测试。