DEV Community

Paramanantham Harrison
Paramanantham Harrison

Posted on • Originally published at learnwithparam.com on

5

Error handling while using native fetch API in JavaScript

Fetch API is very powerful. We can easily send Ajax request using browser fetch API. But it has its own disadvantages too.

One major disadvantage is error handling when using fetch.

Example,

fetch(url).then((response) => {
  // Always gets a response, unless there is network error
  // It never throws an error for 4xx or 5xx response 😟
}).catch(error) => {
  // Only network error comes here
};
Enter fullscreen mode Exit fullscreen mode
  • It always gets a response, unless there is a network error
  • All 4xx, 5xx don’t get into catch block

Error handling in fetch API using promises

First lets see, without handling errors,

fetch(url)
  .then(response => {
    return response.json();
  })
  .then(jsonResponse => {
    // do whatever you want with the JSON response
  });
Enter fullscreen mode Exit fullscreen mode
  • this is bad, because even if the url sends a 404, we send that as response without breaking it.

We can rectify it by throwing error and allow only response which has status code between 200 and 299.

fetch(url)
  .then((response) => {
    if (response.status >= 200 && response.status <= 299) {
      return response.json();
    } else {
      throw Error(response.statusText);
    }
  })
  .then((jsonResponse) => {
    // do whatever you want with the JSON response
  }).catch(error) => {
    // Handle the error
    console.log(error);
  };
Enter fullscreen mode Exit fullscreen mode

This will fix the problem, you can even extract out the checking status part as a function which returns a promise or throw error.

function CheckError(response) {
  if (response.status >= 200 && response.status <= 299) {
    return response.json();
  } else {
    throw Error(response.statusText);
  }
}

// Now call the function inside fetch promise resolver
fetch(url)
  .then(CheckError)
  .then((jsonResponse) => {
  }).catch(error) => {
  };
Enter fullscreen mode Exit fullscreen mode

How to handle fetch errors using async-await syntax

It is same as promises, only the syntax will change. First we will see without error handling,

const response = await fetch(url);
const jsonResponse = await response.json();
console.log(jsonResponse);
Enter fullscreen mode Exit fullscreen mode

example with error handling,

const response = await fetch(url);
if (response.status >= 200 && response.status <= 299) {
  const jsonResponse = await response.json();
  console.log(jsonResponse);
} else {
  // Handle errors
  console.log(response.status, response.statusText);
}
Enter fullscreen mode Exit fullscreen mode

Hope you learnt some tricks in using fetch API, stay tuned for more JavaScript tricks 😇

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay