Working in a error handling problem, where I need to catch error based on status code returned. In addition I need to get the body of the response to get the specific error message. I created a rough script, as follows:
let status = 200;
return fetch('/someurl',{ credentials: 'include' })
.then(res => {
if(!res.ok) {
status = res.status;
}
return res.json();
})
.then(json => {
if(status < 200 || status >= 300) {
notifyError(status, json);
}
treatResponse(json);
})
.catch(err => notifyError(err));
This code works as I expected, but it's not what I would expect in terms of code quality since I'm using a global variable to inform next then what happened in the previous then... very ugly.
I think that my code reflects the fact that I'm new to the fetch api and this promise stuff which I understood but I'm not familiar with.
So can somebody sugest something better?
Thanks