Handling Fetch Errors
You'll learn why fetch() doesn't reject on HTTP errors like 404 or 500, and how to handle them properly.
The Surprising Truth About Fetch Rejections
Many developers expect fetch() to reject its promise when a server returns an error status code like 404 (Not Found) or 500 (Internal Server Error). It doesn't. The fetch() promise only rejects on network failures — situations where the request couldn't be completed at all, like:
- No internet connection
- DNS lookup failure
- Server is unreachable
- Request timeout
If the server responds with any status code (even error codes), fetch() considers that a successful operation and resolves the promise.
Checking Response Status
Since HTTP errors don't cause rejection, you must manually check the ok property or status code on the Response object:
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('Success:', data);
})
.catch(error => {
// Catches BOTH network failures AND our thrown HTTP errors
console.error('Fetch failed:', error);
});
The response.ok property is true only for status codes 200-299. For any other status, you need to handle it yourself — typically by throwing an error to trigger the catch() block.
Think of Fetch Like Mail Delivery
Imagine fetch() as a postal service. A rejection only happens if the letter can't be delivered at all (address doesn't exist). But if it reaches the destination and they respond with "No, go away!" (404), the delivery was technically successful — you just got a rejection letter back. You still need to read that response.
Key Takeaway: Always check response.ok or response.status after a successful fetch, because HTTP error codes don't automatically reject the promise — only network failures do.