如何在promise中链接error.response.json()而不将其嵌套在catch中?

时间:2017-07-28 14:42:35

标签: javascript reactjs bluebird

我正在试图找出处理服务器错误响应承诺的最佳方法

autoload.php

没有将它嵌套在catch()中。有没有办法可以在catch之外完成,但仍然只在出现错误时调用?

error.response.json();

2 个答案:

答案 0 :(得分:0)

  

有没有办法可以在捕获之外完成,但仍然只在出现错误时调用?

没有

  

我试图找出处理服务器错误响应的最佳方法

它有效quite a bit different,但我怀疑你真正想写的是

return doGet(`/rest/hello-world`)
      .then(json => ({
              type: LOAD_SUCCESS,
              data: json.ListResponse.data,
            }),
            error =>
              error.response.json().then(result => ({
                type: LOAD_FAIL,
                error: result.error.message,
              }))
      )
      .then(dispatch);

您可能还想考虑error.response.json()拒绝格式错误的答案的情况。

答案 1 :(得分:0)

您可以使用Response.clone()克隆Response并使用Response对象执行其他任务

fetch("/url")
.then(response => {
  // do stuff with cloned `Response`
  const clone = response.clone();
  clone.json().catch(err => console.log(err));
  return response.json()
})
.then(json => /* do stuff */)