仍然很缺乏经验,我正在尝试错误处理“400 Bad Request”。
我有一个带有搜索栏的网站。
然后,输入到搜索栏中的值将被放入返回对象的 api url 中。
每当输入拼写错误的搜索值时,站点的控制台都会针对 api url 返回“400 错误请求”。
我还从 api url 请求收到下面的错误对象。
{
"meta": {
"code": 400,
"errorType": "failed_geocode",
"errorDetail": "Couldn't geocode param near: Jljjl",
"requestId": "59208ac96a6071641949481d"
},
"response": {}
}
我想要做的是使用如下的条件语句来处理此错误:
try {
if (400 Bad Request) throw "incorrect";
} catch (err) {
document.getElementById('results').innerHTML = "Input is " + err;
}
我已经尝试过像下面这样的条件语句,但似乎我无法访问返回的错误对象中的任何值:
if (object.meta.code === 400)
if (object.meta.code !== 200)
if (object === undefined) // or null or 0
如何将 400 Bad Request 错误放入“if 语句”中,或者是否有其他方法来处理这些错误?
Thanks
Using 获取API https://developer.mozilla.org/en/docs/Web/API/Fetch_API,这可以通过以下方式实现:
fetch(url)
.then((res) => {
if (res.status === 400) {
throw new Error('your error message here');
}
return res.json();
})
.then(json => {
// handle response normally here
})
.catch(ex => {
// handle errors here
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)