我正在使用 redux thunk 在操作中获取一些数据
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
})
)
我的 express 服务器出现错误时返回“一些错误”
return res.status(500).send({ message: 'some error' });
当它获取错误 (500) 时,它的消息是通用的“内部服务器错误”。
我如何在抓取中得到“一些错误”?
最佳答案
不确定您的handleError
中有什么。提取错误消息的一种方法是这样的
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
});
关于javascript - fetch api 从服务器获取错误消息而不是通用消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49784371/