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.
1. Using Try/Catch Blocks
Try-catch blocks are one of the most straightforward ways to handle errors when using Fetch. You can wrap the fetch call in a try block and catch any errors that occur in the catch block.
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.
2. Checking the response status
You can check the response status in the returned Promise to handle server-side errors. The fetch function returns a Promise that resolves to a Response object. This Response object has a status property that indicates the HTTP status code of the response.
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.
3. Handling specific error status codes
Sometimes, you may need to handle specific HTTP error status codes in a specific way. For example, you may want to show a different error message for a 404 Not Found error than for a 500 Internal Server Error. Sometimes, you may want to check for an authorized error response and handle it differently.
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.
4. Combine
We can take all the above error-handling techniques and create a function that makes a Fetch request and uses checks alongside a try/catch to handle errors.
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.
Thank you for this.
It was helpful
Thanks for posting these examples. Looking at example # 2, I was wondering what kind of error would we have to encounter to reach the catch block. Specifically, when would we get a response.ok and still get an error ?
@Mark
The response.ok property will return false if the HTTP status is not successful, i.e., if it’s not within the range 200-299. This is when you would reach the throw new Error line and subsequently the catch block.
well-done
How do i show the error message from my API , example for status code 400. The throw error only shows the statusText