Reputation: 5526
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.
Upvotes: 7
Views: 5885
Reputation: 203231
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;
});
}
}
Upvotes: 9