获取承诺 - 返回500内部服务器错误

时间:2017-01-18 21:18:12

标签: javascript promise fetch

我正在尝试在fetch中处理500个内部服务器错误。如果发生内部错误,服务器将响应消息。我想提取那条消息。

const req = new Request(url, {
      method: node.method,
      mode: 'cors',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(body),
    });
    fetch(req)
      .then((response) => {
        if (response.status === 500) {
          // res.json extracts the body from the response as a promise, chain
          // .then on it and throw an error to be caught in the lower catch.
          response.json()
          .then((json) => {
            const { message, stackTrace } = json;
            throw new ServerException(message, stackTrace); // note 1
          })
          .catch((error) => {
            return Promise.reject(RawException(error)); // note 2
          });
        } else {
          return response.json();
        }
      })
      .then((json) => { // note 3
        dispatch(stopLoading());
        dispatch(recieveResponse(typeOfRequest, json));
      })
      .catch((e) => {
        dispatch(stopLoading());
        dispatch(responseError());
        dispatch(showError(e.message));
      });
  };

我的问题是,提取响应的主体会产生新的承诺,而我无法拒绝内部承诺的外部承诺。

注1触发内部承诺的catch方法。在内部捕获,我已经尝试抛出另一个错误但它似乎不起作用。如果我在第二个注明的行上throw new RawException(error),则没有任何反应,并且第三个注释行上的then方法会触发。如果我在提供的代码中返回被拒绝的承诺,那么仍然会触发,但json未定义。

我该怎么做?

1 个答案:

答案 0 :(得分:4)

解决方案不是嵌套承诺,而是通过结束内部承诺来解决/返回外部承诺的.then

if (response.status === 500) {
  response.json()   // response.json returns a promise, we chose to do nothing with its
  .then((json) => { // conclusion
    const { message, stackTrace } = json;
    throw new ServerException(message, stackTrace); // note 1
  })
  .catch((error) => {
    return Promise.reject(RawException(error)); // note 2
  });
} else {
  return response.json();
}

应该成为

if (response.status === 500) {
  return response.json() // return the result of the inner promise, which is an error
  .then((json) => {
    const { message, stackTrace } = json;
    throw new ServerException(message, stackTrace);
  });
} else {
  return response.json();
}

如果首选语法,也可以删除else子句。 ESLint抱怨其他人是浪费,但我更倾向于使代码的分支明确。

相关问题