首页 文章

HTTP承诺 - 处理错误

提问于
浏览
5

我试图找到一种处理http响应的好方法,我认为这是一个错误 . 我在React Native中使用 fetch . 这是我的代码 .

loginRequest(url) {
  return fetch(url, {
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded;'
    },
    ....
  })
  .then(response => {
    return this.processResponse(response);
  });
}

然后...

processResponse(response) {
    if (response.status === 200) {
      return response.json();
    } else {
      let error = new Error(response.status);
      error.response = response.json(); // This is the problem
      error.status = response.status;
      throw error;
    }
  },

上面的内容如下所示:

return ApiRequests.loginRequest(username, password)
      .then(json => {
        dispatch(Actions.loginSuccess(json, username, password));
      })
      .catch(error => {
        dispatch(Actions.loginFailure(error));
      });
  };

我的想法是,我可以轻松处理所有错误(我们假设除了200错误之外),在catch中 . 问题是response.json()返回一个promise,因此将它分配给error.response是行不通的 . 我需要跟踪http状态代码和响应正文 .

1 回答

  • 6

    这个怎么样:

    processResponse(response) {
      if (response.status === 200) {
        return response.json();
      } else {
        return response.json().then((data) => {
          let error      = new Error(response.status);
          error.response = data;
          error.status   = response.status;
          throw error;
        });
      }
    }
    

相关问题