Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 723
Giannis Avatar asked May 31 '16 09:05

Giannis


People also ask

How does Promise all handle errors?

Promise. all is all or nothing. It resolves once all promises in the array resolve, or reject as soon as one of them rejects. In other words, it either resolves with an array of all resolved values, or rejects with a single error.

How do you handle Promise reject error?

catch " around the executor automatically catches the error and turns it into rejected promise. This happens not only in the executor function, but in its handlers as well. If we throw inside a . then handler, that means a rejected promise, so the control jumps to the nearest error handler.

What happens when a Promise throws an error?

The Promise returned by catch() is rejected if onRejected throws an error or returns a Promise which is itself rejected; otherwise, it is fulfilled.

What happens if Promise is not resolved?

So failing to resolve or reject a promise just fails to ever change the state from "pending" to anything else. This doesn't cause any fundamental problem in Javascript because a promise is just a regular Javascript object.


1 Answers

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;
    });
  }
}
like image 52
robertklep Avatar answered Oct 10 '22 01:10

robertklep