Blog>
Snippets

Handling HTTP Errors for Fetch Requests

Demonstrate how to gracefully handle HTTP errors when making cross-origin requests using Fetch API.
function handleErrors(response) {
    if (!response.ok) {
        throw Error(response.statusText);
    }
    return response;
}
This function checks if the response status is not 'ok', which indicates that the HTTP request was not successful. If it wasn't, it throws an error with the status text of the response.
function fetchWithErrorHandler(url) {
    return fetch(url)
        .then(handleErrors)
        .then(response => response.json())
        .catch(error => console.error('Fetch Error:', error));
}
This function uses fetch to retrieve data from the given URL. It then calls the 'handleErrors' function to check the response. If 'handleErrors' throws an error, the 'catch' block logs the error. Otherwise, it processes the JSON response.