简体   繁体   中英

HTTP Promise - Handling Errors

I am trying to find a nice way of handling http responses that I consider an error. I am using fetch in React Native. Here is my code.

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

Then...

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

And the above are called like this:

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

The idea is that I can easily handle all the errors separately (we assume anything but 200 error), within the catch. The problem is that response.json() returns a promise, so assigning it to error.response is not working. I need to keep track of http status code and the response body.

How about this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM