Error handling with the Fetch API

Mon Mar 27 2023

4 min read

Error handling is an essential part of web development, and it can significantly affect how users experience your web application.

In this guide, we'll focus on error handling with the Fetch API, a powerful tool for making API requests in JavaScript.

Fetch API

Fetch is a JavaScript API used to make API requests. It allows you to send and receive server data using various methods such as GET, POST, PUT, DELETE, etc. You can learn more about Fetch API here.

Fetch API Error Handling

The Fetch API is a way to make API requests in JavaScript, and it returns a Promise that can either resolve with a Response object or reject with an error. Network errors are considered failures to establish a network connection, perform a DNS lookup, or complete the request within a certain timeframe. The Promise will reject with a NetworkError object if there is one.

Handling Response Errors

Several types of errors can occur when using the Fetch API. Here are some common errors and ways to fix them.

API key error

In this example, let's say we're trying to access the weather data for London using the OpenWeatherMap API from Rapid API Hub.

Loading component...

Image, we're passing an invalid API key. If an "invalid API key" error occurs, the catch block will catch the error. We can then check if the error is a TypeError and the error message includes the phrase "API key", which would indicate an API key error.

js
fetch("https://open-weather13.p.rapidapi.com/city/landon", {
"method": "GET",
"headers": {
"x-rapidapi-key": "invalid-key",
"x-rapidapi-host": "open-weather13.p.rapidapi.com"
}
})
.then(response => {
if (!response.ok) {
throw new Error('Network error');
}
return response.json();
})
.then(data => {
// Do something with the data
})
.catch(error => {
if (error instanceof TypeError && error.message.includes('API key')) {
console.error('Invalid API key:', error);
} else {
console.error('There was a problem with the Fetch operation:', error);
}
});

Network errors

These occur when the Fetch API cannot connect to the server, or there is a problem with the network connection. Examples include "Failed to fetch" or "Network error". To solve this error, you should check your network connection and make sure the server is running.

js
fetch('http://example.com/api/data.json')
.then(response => {
if (!response.ok) {
throw new Error('Network error');
}
return response.json();
})
.then(data => {
// Do something with the data
})
.catch(error => {
console.error('There was a problem with the Fetch operation:', error);
});

CORS errors

These occur when the server you are trying to access does not allow your origin to make requests to it. Examples include "Access to fetch at http://example.com/data.json from origin 'http://localhost:3000' has been blocked by CORS policy".

To solve this error, you need to configure the server to allow cross-origin requests.

js
fetch('http://example.com/api/data.json', {
mode: 'cors',
headers: {
'Access-Control-Allow-Origin': '*',
},
})
.then(response => response.json())
.then(data => {
// Do something with the data
})
.catch(error => {
console.error('There was a problem with the Fetch operation:', error);
});

To learn more about CORS, click here.

Server errors

This error occurs when the server returns an error status code, such as 404 or 500. Examples include "404 Not Found" or "500 Internal Server Error". To solve this error, you should check the server logs and fix any issues with the server-side code.

js
fetch('http://example.com/api/data.json')
.then(response => {
if (!response.ok) {
throw new Error('Server returned ' + response.status);
}
return response.json();
})
.then(data => {
// Do something with the data
})
.catch(error => {
console.error('There was a problem with the Fetch operation:', error);
});

Wrap up

That’s all for this guide. Now you know how to handle errors with the Fetch API and the various errors that can occur during requests.

We have written several guides on how to get started with Fetch API.