[英]JS Promises - catch() doesn't return anything
我正在以这种方式从 API 获取数据,如果用户搜索无效城市但无法正常工作,我会尝试捕获 404 错误。
const search = evt => { if (evt.key === "Enter") { fetch(`${api.base}weather?q=${query}&units=metric&APPID=${api.key}`) .then(res => res.json()) .then(result => { setWeather(result); setQuery(''); }).catch(() => console.log("error")); } }
请参阅文档: https : //developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
即使响应是 HTTP 404 或 500,从
fetch()
返回的 Promise也不会拒绝 HTTP 错误状态。相反,它会正常解决(ok
状态设置为 false),并且只会在网络故障或如果有任何阻止请求完成。
您必须使用.then(response => {...})
提供的响应参数并检查response.ok
或response.status
以获得 404(或 500)错误。
您的代码运行良好,如您所见:
const search = evt => { if (evt.key === "Enter") { fetch('http://dfsdfsdfdsfsdfdfs.com') .then(res => res.json()) .catch(() => console.log("error")); } } search({key : 'Enter'});
但是来自服务器的错误代码不被视为fetch
错误,因此您必须自己解析响应并做出相应的反应。 如果状态代码在 200-299 范围内,您可以使用res.ok
返回 true。 有关更多信息,您可以查看响应对象文档
正如docs
,由于fetch
不会对404
或500
状态进行捕获,因此您可以通过抛出错误并在catch
部分进行catch
来模拟该行为。
fetch(`${api.base}weather?q=${query}&units=metric&APPID=${api.key}`)
.then((response) => {
if(response.status == 404){
throw '404 page not found';
}
return response.json();
})
.then((response) => {
console.log('your JSON string ',response);
})
.catch((err) => {
console.error(err);
});
我能够以这种方式得到错误:
const search = evt => { if (evt.key === "Enter") { fetch(`${api.base}weather?q=${query}&units=metric&APPID=${api.key}`) .then(res => res.json()) .then(result => { setWeather(result); setQuery(''); }).then((data) => { if (data === undefined) { alert("City not found"); } }); } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.