Ask any question about JavaScript here... and get an instant response.
How can I handle errors gracefully with fetch when the API returns a non-JSON response?
Asked on Nov 07, 2025
Answer
When using the Fetch API, you can handle errors gracefully by checking the response status and content type before attempting to parse the response as JSON. This ensures that you handle non-JSON responses appropriately.
<!-- BEGIN COPY / PASTE -->
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
const contentType = response.headers.get('content-type');
if (contentType && contentType.includes('application/json')) {
return response.json();
} else {
throw new Error('Received non-JSON response');
}
})
.then(data => {
console.log('Data:', data);
})
.catch(error => {
console.error('Fetch error:', error);
});
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The "fetch" function initiates a network request to the specified URL.
- Check "response.ok" to ensure the HTTP status code is in the 200-299 range.
- Verify the "content-type" header to confirm the response is JSON before parsing.
- Use "catch" to handle any errors that occur during the fetch or parsing process.
Recommended Links:
