The Fetch API is a modern and efficient way to retrieve resources from a server. It is an interface that provides a unified way to fetch resources from different sources. Fetch makes sending HTTP requests, including GET and POST, easy and handles responses asynchronously.
However, handling errors properly is important when working with the Fetch API. Errors can occur for various reasons, such as a network error, a server-side error, or an invalid URL. Failing to handle these errors can result in unexpected behaviour and break your application.
This article will look at several ways to handle errors using the Fetch API with Async/Await.
async function fetchData(url) { try { const response = await fetch(url); const data = await response.json(); // Use the data as needed } catch (error) { console.error(error); }}
This approach is easy to implement and works well for basic error handling. However, it only works for errors thrown by the fetch function itself. If the response from the server indicates an error, such as a 404 Not Found or 500 Internal Server Error, this approach won’t catch those errors.
async function fetchData(url) { try { const response = await fetch(url); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.json(); // Use the data as needed } catch (error) { console.error(error); }}
In this example, we use the response.ok property, which returns a Boolean indicating whether the HTTP status code is in the 200-299 range (i.e., a success status). If the response is not okay, we throw a new error that includes the HTTP status code.
async function fetchData(url) { const response = await fetch(url); if (response.status === 404) { throw new Error('Page not found'); } else if (response.status === 500) { throw new Error('Server error'); } else if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.json(); return data;}
This example uses a series of if statements to handle specific HTTP status codes. We throw different errors for each HTTP status code and catch them in the calling code if needed.
async function fetchData(url) { try { const response = await fetch(url); if (response.status === 404) { throw new Error('Page not found'); } else if (response.status === 500) { throw new Error('Server error'); } else if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.json(); return data; } catch (error) { console.error(error); }}
This function uses a try-catch block to handle errors thrown by the fetch function. It also checks the response status to handle server-side errors and specific HTTP error status codes. If an error occurs, it logs the error to the console.
You can use this function or modify it to fit your specific needs.
For example, you could add additional error-handling logic or display an error message to the user instead of logging the error to the console. Or, use ranges instead of specific status code checks. But, as you can see, error handling with Fetch is a breeze. It’s a lot nicer than the days of using XMLHttpRequest.
The post Handling Errors with the Fetch API appeared first on I Like Kill Nerds.