HTTP Promise - 处理错误

HTTP Promise - Handling Errors

我正在尝试找到一种很好的方法来处理我认为是错误的 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));
      });
  };

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

这个怎么样:

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;
    });
  }
}