Fetch error handling

Handling Fetch errors, Fetch never fails

The Fetch API in the browser provides an excellent medium to make HTTP transactions over the network. Using the fetch method we can access this with our friendly neighborhood JavaScript ✨

TLDR; Fetch is awesome, fetch is cool but, when it comes to error handling things are a bit different here and it can be quite confusing in the beginning, and in this post, we’ll handle this problem step by step.

A simple fetch

Below is the code for a simple fetch, plain JavaScript nothing fancy.

fetch("https://httpstat.us/404")
  .then((response) => console.log("Result 👉", response))
  .catch((error) => console.log("Something went wrong 💔"));

If the request is successful all good but, let’s say something went wrong then the browser shows the following output in the console.

GET https://httpstat.us/404 404
Result 👉 Response {...}

We weren’t able to identify the error, and there are two more problems here. First, the promise that the fetch method returns is fulfilled and not rejected because fetch only rejects when there are network errors. Wait, what? Yes we might get 4XX or 5XX errors however fetch wouldn’t throw an error unless we are offline or lose network connectivity. This is the reason the catch block wasn’t executed.

Now, this takes us to our second problem. Generally, we might wanna know the reason why our request failed so that we can fix/handle errors and we might expect a 404 or 500 as the reason for failure, even this wasn’t possible.

The solution

The Obstacle is the way ~ Ryan Holiday
Yes, the fetch method provides an ok flag to let us know whether an HTTP request is successful/failed. The response.ok flag will be false when we get errors and we can use it to handle error scenarios.

fetch("https://httpstat.us/404")
  .then((response) => {
    if (!response.ok) {
      throw Error(response.status);
    }
    console.log("Result 👉", response);
  })
  .catch((error) => {
      console.log("Something went wrong 💔", error.message)
  });

// Output
Something went wrong 💔 404

Fetch with Async Await

I’ve written this piece of code when I started learning about Fetch and how it works. Below I haven’t but, it is a common practice to create a separate function to detect and handle fetch errors.

async function fetchData(url) {
  const response = await fetch(url);
  /**
   * Detect 4xx - 5xx errors,
   * response.ok will be false on failure.
   * */
  if (!response.ok) {
    throw new Error(response.status);
  }
  const data = await response.json();
  /**
   * Handle special cases where the data recieved
   * is empty, undefined and invalid
   */
  if (!data || !data.length) {
    throw new Error("Invalid data received.");
  }
  return data;
}

fetchData("https://httpstat.us/500")
.then(data => console.log(data))
.catch( error => console.log("🔴 Error Code :", error.message));

// Output
🔴 Error Code : 500

Reference: Fetch API MDN

Read more: articles on async

Tags: