Graceful Fallback for Unknown Actions with Fetch
Show how to implement a fallback function when an API endpoint is not found while using the fetch API.
function handleUnknownAction(endpoint, fallbackAction) {
fetch(endpoint)
.then(response => {
if (!response.ok) {
if (response.status === 404) {
// If the response status is 404 (Not Found),
// call the fallback function
console.error(`Endpoint not found: ${endpoint}`);
fallbackAction();
} else {
// Handle other HTTP status codes
throw new Error(`An error occurred: ${response.statusText}`);
}
}
return response.json();
})
.then(data => {
// Process the data from the API
console.log(`Data received from ${endpoint}`, data);
})
.catch(error => {
// Handle any errors that occurred during the fetch
console.error('Fetch error:', error);
});
}
This function, `handleUnknownAction`, takes two arguments: an API `endpoint` and a `fallbackAction` function. The function makes a fetch request to the endpoint; if the response is not successful and the status is 404, it logs an error and calls the fallbackAction. If the status code is different, it throws an error. If the fetch is successful, it processes the JSON data. All fetch errors are caught and logged in the catch block.