首页 文章

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

提问于
浏览
1

我试图在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触发内部promise的catch方法 . 在内部捕获,我尝试抛出另一个错误但它似乎不起作用 . 如果我在第二个提到的行上 throw new RawException(error) ,则没有任何反应,并且第三个注意到的行上的 then 方法会触发 . 如果我在提供的代码中返回被拒绝的promise,那么仍然会触发但是json未定义 .

我该怎么做呢?

1 回答

  • 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抱怨其他人是浪费,但我更喜欢它使代码的分支明确的方式 .

相关问题