提取:如果状态不正常,则拒绝承诺并捕获错误? [英] Fetch: reject promise and catch the error if status is not OK?
本文介绍了提取:如果状态不正常,则拒绝承诺并捕获错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这就是我要去的地方
import 'whatwg-fetch';
function fetchVehicle(id) {
return dispatch => {
return dispatch({
type: 'FETCH_VEHICLE',
payload: fetch(`http://swapi.co/api/vehicles/${id}/`)
.then(status)
.then(res => res.json())
.catch(error => {
throw(error);
})
});
};
}
function status(res) {
if (!res.ok) {
return Promise.reject()
}
return res;
}
承诺不会被拒绝,这就是我要弄清楚的.
The promise doesn't get rejected, that's what I'm trying to figure out.
我正在Redux中将获取polyfill 和
I'm using this fetch polyfill in Redux with redux-promise-middleware.
推荐答案
提取仅在发生网络错误时承诺以TypeError拒绝.由于4xx和5xx响应不是网络错误,因此没有任何问题.您需要自己引发错误才能使用Promise#catch
.
Fetch promises only reject with a TypeError when a network error occurs. Since 4xx and 5xx responses aren't network errors, there's nothing to catch. You'll need to throw an error yourself to use Promise#catch
.
获取响应方便地提供了 ok
,它告诉您请求是否成功.这样的事情应该可以解决问题:
A fetch Response conveniently supplies an ok
, which tells you whether the request succeeded. Something like this should do the trick:
fetch(url).then((response) => {
if (response.ok) {
return response.json();
} else {
throw new Error('Something went wrong');
}
})
.then((responseJson) => {
// Do something with the response
})
.catch((error) => {
console.log(error)
});
这篇关于提取:如果状态不正常,则拒绝承诺并捕获错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文