fetch api 从服务器获取错误消息而不是通用消息 [英] fetch api get error messages from server rather than generic messages
本文介绍了fetch api 从服务器获取错误消息而不是通用消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 redux thunk 在一个动作中获取一些数据
I'm using redux thunk to fetch some data in an action
function handleErrors(response) {
console.log(response)
if (!response.ok) {
throw Error(response.statusText);
}
return response;
}
export const something = (var) => dispatch => {
fetch(`${url}/something`, {credentials: 'include'})
.then(handleErrors)
.then(res => res.json())
.then(res =>
dispatch({
type: SOMETHING,
payload: res
})
)
.catch(error =>
dispatch({
type: ERROR,
payload: error
})
)
我的快递服务器出现错误时响应一些错误"
my express server on an error responds with 'some error'
return res.status(500).send({ message: 'some error' });
当它获取并且出现错误 (500) 时,它的消息是通用的内部服务器错误".
when it fetches and it's an error (500), its message is the generic "Internal Server Error".
我如何在 fetch 中得到一些错误"?
how do I get the 'some error' in fetch?
推荐答案
不确定您的 handleError
中有什么.提取错误消息的一种方法是这样的
Not sure what’s in your handleError
. One approach to extract the error message would be something like this
fetch(url)
.then(res => {
// Check if response has errors
if (res.ok) {
// No errors
return res.json();
} else {
// Has errors, since res.json() returns a Promise, we
// chain a then here to get the value and return the err value
// as Promise rejection so that it will go to the
// catch handler
return res.json().then(err => Promise.reject(err));
// this could also be
// return res.json().then(err => throw Error(err));
}
})
.then(json => {
// dispatch success
})
.catch(err => {
// dispatch error
});
这篇关于fetch api 从服务器获取错误消息而不是通用消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文