Coding Triumph

Helpful code snippets & tutorials

How to handle failed HTTP requests and network errors with the Fetch API

The Fetch API is a promise-based JavaScript interface for manipulating HTTP requests and responses. It’s native to all modern browsers and offers a simple way to fetch resources over the network. Although it may initially seem confusing, the API is really intuitive once you wrap your head around it. The same can be said for error handling: It’s a little bit tricky at first but simple enough when you get used to it.

Two types of errors can occur while sending a request to a server with the Fetch API: network errors and HTTP errors (5xx and 4xx). The fetch() function will throw an exception for network errors but not for HTTP errors. It may look counter-intuitive, especially if you are familiar with other HTTP libraries such as axios or jQuery’s ajax.

fetch(url).then((response) => {
  // all responses are handled gere (1xx, 2xx, 3xx, 4xx, and, 5xx
  // does not throw an error for 4xx or 5xx response 😟
}).catch((error) => {
  // only network error are caught here
});

Let’s see how we can fix this issue.

1. Handling fetch() errors with promises:

The solution to this problem is simple. All we have to do is to manually throw an exception whenever an HTTP error happens.

fetch(url)
  .then(response => {
    // if the request was successful
    if (response.status >= 200 && response.status <= 299) {
      // handle the response
      return response.json();
    } else {
      // throw an exception for HTTP errors (4xx and 5xx)
      throw Error(response.statusText);
    }
  })
  .then(json => {
    // do whatever you want with the data
    console.log(json)
  })
  .catch(error => {
    // now we can handle both HTTP errors and nework errors
    console.log(error);
  });

2. Handling fetch() errors with async/await:

Like with promises, we can do the same with async/await. Only the syntax changes:

try {
  const response = await fetch(url);
  if (response.status >= 200 && response.status <= 299) {
    const json = await response.json();
    // do what you want with the data
    console.log(json);
  } else {
    // throw an exception for HTTP errors (4xx and 5xx)
    throw Error(response.statusText);
  }
} catch (error) {
    // now we can handle both HTTP errors and nework errors
    console.log(error)
}

Conclusion:

In this post, I’ve shown you how to handle network and HTTP errors with the Fetch API. I hope you learned some new tricks. Stay tuned for more JavaScript tutorials.

If you like this post, please share
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments