Ask any question about JavaScript here... and get an instant response.
How do I handle a fetch request error when the API returns a non-200 status code and still parse the JSON response?
Asked on Dec 05, 2025
Answer
To handle a fetch request error when the API returns a non-200 status code and still parse the JSON response, you can check the response status and handle it accordingly. Here's a clean example:
<!-- BEGIN COPY / PASTE -->
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
return response.json().then(errorData => {
throw new Error(`Error: ${response.status} - ${errorData.message}`);
});
}
return response.json();
})
.then(data => {
console.log('Data:', data);
})
.catch(error => {
console.error('Fetch error:', error.message);
});
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The "fetch" function is used to make the request to the API.
- The "response.ok" property checks if the status code is in the range 200-299.
- If the response is not "ok", the JSON error data is parsed, and an error is thrown with a custom message.
- The "catch" block handles any errors, including network issues or the custom error thrown for non-200 status codes.
Recommended Links:
