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.
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.
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.
The Promise returned by catch() is rejected if onRejected throws an error or returns a Promise which is itself rejected; otherwise, it is fulfilled.
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.
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;
});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With