J. Pedro Ribeiro

Error Handling in Fetch

May 27, 2023

network output

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");
    } 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.

J. Pedro Ribeiro

I’m a Brazilian front-end developer living in London. This website features some of my latest projects and my thoughts on anything web related.
You can find me on Twitter, Instagram, and LinkedIn.
Wanna talk? Send me a message.