Reputation: 3891
Using fetchApi I am issuing a POST request to an endpoint and catching errors like this:
fetch(new Request(url, {
method: 'POST',
headers: { ...defaultHeaders, ...headers } ,
credentials: 'include',
body: JSON.stringify(body)
})).then(
// handle correct reponse
).catch(
if (err.status === 401) {
// handle error nicely
} else if (err.status === 429) {
// handle error differently
} else {
// handle error yet another way
}
);
While 401 error is handled as expected, when the endpoint responds with 429 the code
else if (err.status === 429) {
// handle error differently
}
Is never executed.
EDIT1: the entire catch is never reached in case of 429
Are 401 and 429 status codes handled differently by javascript/browsers? How Can I catch 429 error and handle it my way?
Upvotes: 7
Views: 6605
Reputation: 521995
Looks mostly like wrong expectations. The promise will only be rejected (and hence catch
invoked) when the response's type
is "error"
, which only seems to be the case for very specific, limited cases.
Per MDN, the
fetch()
API only rejects a promise when a “network error is encountered, although this usually means permissions issues or similar.” Basicallyfetch()
will only reject a promise if the user is offline, or some unlikely networking error occurs, such a DNS lookup failure.
In other words, a request with a 429 response is still a successfully executed request.
The good is news is fetch provides a simple
ok
flag that indicates whether an HTTP response’s status code is in the successful range or not.fetch("http://httpstat.us/500") .then(function(response) { if (!response.ok) { throw Error(response.statusText); } })
Upvotes: 10