Have you ever wrapped your fetch on a try/catch block to catch 4xx and 5xx errors, and it didn't work?
try {
const response = await fetch("https://httpstat.us/500");
console.log(response);
} catch (error) {
console.log(error); // This will never be called!
}This happens to me more frequently than I would like to admit.
The reason why it doesn't work is that fetch will only throw error if there is a network error (or something like CORS).
A 4xx or 5xx is a server response and therefore not considered an error by fetch.
So what you need to do is to check the response.ok property, which will be true if the response is 200:
let response;
try {
// Change the ending of the url below to 200 for a success response
response = await fetch("https://httpstat.us/400");
if(response.ok) {
// Carry on...
console.log("All good ✅");
} else {
throw (
`Error: Response status ${response.status}`
);
}
} catch(e) {
// Handle error
console.log(e); // Logs "Error: Response status 400"
}Below is a working example on CodePen:
And there you go.
Now you know how to handle errors in fetch!
Or, if you are like me, you'll be here next month looking for this post again.