Checking Response Status
You'll learn how to properly inspect HTTP response status codes to distinguish successful API calls from errors.
The Core Problem
When you make a fetch() request, JavaScript doesn't automatically throw an error for HTTP error status codes like 404 or 500. A failed HTTP request still resolves the Promise successfully! This means you need to manually check whether the response represents success or failure.
The Two Essential Properties
response.ok
This boolean property tells you at a glance if the response was successful. It's true for status codes in the 200–299 range (success codes) and false for everything else:
fetch('https://api.example.com/users')
.then(response => {
if (!response.ok) {
throw new Error('Request failed');
}
return response.json();
});
response.status
This number gives you the exact HTTP status code (like 200, 404, 500). Use it when you need to handle specific codes differently:
fetch('https://api.example.com/data')
.then(response => {
if (response.status === 404) {
console.log('Resource not found');
} else if (response.status === 500) {
console.log('Server error');
} else if (!response.ok) {
console.log('Other error:', response.status);
}
return response.json();
});
Why This Matters
Think of fetch() like a postal service: it successfully delivers the letter even if the letter contains bad news. The delivery itself didn't fail—but the content might indicate failure. You must open the envelope (response.ok / response.status) to find out.
Key Takeaway: Always check response.ok or response.status before processing response data—fetch() won't automatically reject failed HTTP requests for you.