Ask any question about JavaScript here... and get an instant response.
How can I handle a 404 error gracefully when using fetch to call an API and parse JSON in JavaScript?
Asked on Nov 05, 2025
Answer
To handle a 404 error gracefully when using "fetch" to call an API and parse JSON, you can check the response status and handle errors accordingly.
<!-- BEGIN COPY / PASTE -->
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then(data => {
console.log('Data received:', data);
})
.catch(error => {
console.error('There was a problem with the fetch operation:', error);
});
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The "fetch" function is used to make an API call.
- The "response.ok" property checks if the response status is in the range 200-299.
- If the response is not ok, an error is thrown with the status code.
- The "response.json()" method parses the response as JSON if the response is successful.
- The "catch" block handles any errors that occur during the fetch operation.
Recommended Links:
