Javascript 获取:拒绝承诺并在状态不正常时捕获错误?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38235715/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fetch: reject promise and catch the error if status is not OK?
提问by Vlady Veselinov
Here's what I have going:
这是我要做的:
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;
}
EDIT: The promise doesn't get rejected, that's what I'm trying to figure out.
编辑:承诺不会被拒绝,这就是我想要弄清楚的。
I'm using this fetch polyfillin Redux with redux-promise-middleware.
我在 Redux 中使用这个fetch polyfill和redux-promise-middleware。
回答by fny
Fetchpromises 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
.
当发生网络错误时,Fetch承诺只会以 TypeError 拒绝。由于 4xx 和 5xx 响应不是网络错误,因此没有什么可捕获的。您需要自己抛出错误才能使用Promise#catch
.
A fetch Responseconveniently supplies an ok
, which tells you whether the request succeeded. Something like this should do the trick:
一个fetch Response方便地提供一个ok
,它告诉你请求是否成功。像这样的事情应该可以解决问题:
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)
});
回答by Vlady Veselinov
Thanks for the help everyone, rejecting the promise in .catch()
solved my issue:
感谢大家的帮助,拒绝承诺.catch()
解决了我的问题:
export 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 => {
return Promise.reject()
})
});
};
}
function status(res) {
if (!res.ok) {
throw new Error(res.statusText);
}
return res;
}
回答by Torsten Barthel
I just checked the status of the response object:
我刚刚检查了响应对象的状态:
$promise.then( function successCallback(response) {
console.log(response);
if (response.status === 200) { ... }
});