从服务器获取Fetch API错误信息而不是通用信息。

3
我正在使用redux thunk在一个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
        })
    )

我的Express服务器在出现错误时会响应“some error”

return res.status(500).send({ message: 'some error' });

当它获取数据时,如果出现错误(500),其消息将是通用的“内部服务器错误”。

我如何在获取数据时获得“一些错误”?


请尝试访问此链接:github.com/github/fetch/issues/203#issuecomment-143347675 - Usman Iqbal
1个回答

7

不确定你的 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
  });

你可以使用这个答案中的第一个 then 替换你的 handleError 函数,并删除 .then(res) => res.json() - jpdelatorre
请问您能否解释一下,您的代码如何获取实际响应而不是通用响应? - totalnoob
更新了我的回答并加入了一些解释。希望有所帮助。 - jpdelatorre
@totalnoob 如果有任何不清楚的地方,请告诉我,否则请接受这个答案。 - jpdelatorre
当我使用上述方法时,出现了以下错误: “未捕获的(在承诺中)SyntaxError:意外的 JSON 输入结束” 我该如何修复它? - Yossi Sternlicht

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接