Why does fetch() NOT reject its Promise for HTTP error responses like 404 or 500?
Short answer
fetch() only rejects for network-level failures (DNS errors, no connectivity, CORS block) — any response the server actually sends, including error status codes, resolves successfully. You must check response.ok (or response.status) yourself and throw manually if needed.
Advertisement
AModel answer
fetch() only rejects for network-level failures (DNS errors, no connectivity, CORS block) — any response the server actually sends, including error status codes, resolves successfully. You must check response.ok (or response.status) yourself and throw manually if needed.
const res = await fetch('/api/missing');
if (!res.ok) {
throw new Error(`HTTP ${res.status}: ${res.statusText}`);
}
const data = await res.json();Real-world example
A bug where a failed API call with a 500 status was silently treated as success because .ok wasn't checked.
Likely follow-ups
- How would you wrap fetch() in a helper that automatically throws on non-OK responses?
Related topics