Just Learn Code

Handling Fetch API Errors: Strategies for Smooth Web Development

As web developers, we are all familiar with the Fetch API, which provides an interface for fetching resources asynchronously. Fetch requests return a Promise that resolves into a Response object.

The Response object contains properties and methods that allow us to access data, check the server’s response status, and handle errors appropriately. In this article, we will explore two critical topics related to fetching data using Fetch API.

First, we will learn how to retrieve the status code of an HTTP response. Second, we will discuss how to handle errors in fetch requests.

Getting the Status Code of a Fetch HTTP Response

When we make a fetch call, the server responds with an HTTP response. The HTTP response contains a status code, which indicates whether the request was successful or not.

We can retrieve the status code of a fetch response using the `status` property of the Response object. To access the `status` property, we need to grab the Response object returned from the fetch() call and call the `status` property on it.

“`javascript

fetch(‘https://jsonplaceholder.typicode.com/posts/1’)

.then(response => {

console.log(response.status)

})

.catch(error => console.error(error))

“`

In the above example, we make a fetch call to retrieve data from a JSON API. We then grab the Response object and call `status` to get the status code of the response.

In this case, the status code will be 200, which means the request was successful. We can also use a try-catch block to handle errors when accessing the `status` property.

Here’s how we can do that:

“`javascript

try {

const response = await fetch(url);

console.log(response.status);

} catch(error) {

console.error(error);

}

“`

In the above example, we use `try-catch` to handle errors when accessing the ‘status’ property. If an error occurs, it’s caught by the `catch` block, and we log the error to the console.

Handling Errors with Fetch Requests

Errors can occur in fetch requests due to network issues, server errors, or incorrect data. It’s essential to handle these errors appropriately to ensure that users have the best experience while using our web application.

Here are some strategies we can use to handle errors in fetch requests. Using response.ok Property to Check Server Response

The `ok` property is a boolean value that indicates whether the server response was successful or not.

A server response is considered successful if the status code falls within the range of 200 to 299. We can use the `ok` property to check whether the server response was successful or not.

Here’s an example:

“`javascript

fetch(‘https://jsonplaceholder.typicode.com/posts/1’)

.then(response => {

if(response.ok) {

// Do something with the response

} else {

throw Error(‘Response not OK’);

}

})

.catch(error => console.error(error.message));

“`

In the above example, we check the `ok` property of the Response object to determine whether the server response was successful or not. If the response is not OK, we throw an error.

Throwing Error if Request Was Not Successful

If we encounter an error while processing a fetch request, we can throw an error. Throwing an error stops the execution of the fetch request and jumps to the `catch` block, where we can handle the error.

“`javascript

fetch(‘https://jsonplaceholder.typicode.com/posts/1’)

.then(response => {

if(!response.ok) {

throw Error(‘Response not OK’);

}

return response.json();

})

.then(data => console.log(data))

.catch(error => console.error(error));

“`

In the above example, we use the same `ok` property to check if the server response was successful. If the response is not OK, we throw an error.

In the next `.then()` block, we process the data if the response is OK.

Automatic Rejection of Promise for Network Error

Fetch requests can fail if there is a network error or if the server blocks our CORS requests. In such cases, the Promise will be rejected automatically, and the error will be caught by the `catch` block.

“`javascript

fetch(‘https://domain-that-does-not-exist.com’)

.then(response => response.json())

.then(data => console.log(data))

.catch(error => console.error(error.message));

“`

In this example, we try to fetch data from a domain that does not exist. The Promise is rejected automatically, and we catch the error in the `catch` block.

Conclusion

In this article, we learned how to retrieve the status code of a fetch response using the `status` property of the Response object. We also learned different strategies to handle errors in fetch requests, including using the `ok` property to check the server response, throwing errors if the request was not successful, and handling network errors with automatic promise rejections.

By using these strategies, we can ensure that our web applications provide a smooth experience for our users. In this article, we discussed two crucial topics related to fetching data using Fetch API: getting the status code of an HTTP response and handling errors in fetch requests.

We learned how to retrieve the status code using the `status` property of the Response object and discussed various strategies to handle errors, including using the `ok` property to check the server response, throwing errors if the request was not successful, and handling network errors with automatic promise rejections. By using these strategies, we can ensure that our web applications provide a smooth experience for our users and improve our web development skills.

Remember to access the status code, check server responses and handle errors to avoid mistakes and provide a better experience for users.

Popular Posts