Safe Data Fetching and Improving Error Handling with Fetch API in Modern JavaScript

Zamin Mirzad
4 min readSep 15, 2023

Introduction:
The Fetch API in JavaScript is a powerful tool for making network requests, but handling errors and response data can be challenging. In this article, we’ll explore various approaches to improve error handling and enhance the Fetch API for more efficient and reliable data retrieval.

Safe data fetching in modern javascript

The Default Approach
The standard approach to using Fetch often involves code like this:

{
const res = await fetch('/user');
const user = await res.json();
}

While this approach is straightforward, it has several issues, primarily related to error handling.

Handling Errors
To address error handling, we can use try-catch blocks:


try {
const res = await fetch('/user');
const user = await res.json();
} catch (err) {
// Handle the error
}

However, this approach still leaves room for improvement, as it assumes a successful response without considering potential non-200 status codes.

A Safer Approach
A safer approach involves checking the response status code:

try {
const res = await fetch('/user');

if (!res.ok) {
switch…

--

--

Zamin Mirzad

I'm Software Developer and I'm dedicated to continuous learning and excited to share my insights and experiences on Medium. Let's learn together