gotchajavascriptMajorpending
Gotcha: fetch() does not throw on HTTP errors
Viewed 0 times
fetchresponse.okHTTP-errorstatusrejectnetwork
Error Messages
Problem
fetch() only rejects on network failures, not on HTTP error status codes (404, 500, etc.). A 500 response is treated as a successful fetch.
Solution
Always check response.ok or response.status:
// BAD - doesn't catch 404/500:
try {
const data = await fetch('/api/user').then(r => r.json());
} catch (e) {
// Only catches network errors, NOT 404/500!
}
// GOOD - check response.ok:
const response = await fetch('/api/user');
if (!response.ok) {
throw new Error(
}
const data = await response.json();
// Helper function:
async function fetchJSON(url, options) {
const response = await fetch(url, options);
if (!response.ok) {
const body = await response.text();
throw new Error(
}
return response.json();
}
// What fetch DOES reject for:
// - Network errors (offline, DNS failure)
// - CORS errors
// - Request aborted via AbortController
// What fetch does NOT reject for:
// - 4xx errors (400, 401, 403, 404)
// - 5xx errors (500, 502, 503)
// - Any valid HTTP response
// BAD - doesn't catch 404/500:
try {
const data = await fetch('/api/user').then(r => r.json());
} catch (e) {
// Only catches network errors, NOT 404/500!
}
// GOOD - check response.ok:
const response = await fetch('/api/user');
if (!response.ok) {
throw new Error(
HTTP ${response.status}: ${response.statusText});}
const data = await response.json();
// Helper function:
async function fetchJSON(url, options) {
const response = await fetch(url, options);
if (!response.ok) {
const body = await response.text();
throw new Error(
HTTP ${response.status}: ${body});}
return response.json();
}
// What fetch DOES reject for:
// - Network errors (offline, DNS failure)
// - CORS errors
// - Request aborted via AbortController
// What fetch does NOT reject for:
// - 4xx errors (400, 401, 403, 404)
// - 5xx errors (500, 502, 503)
// - Any valid HTTP response
Why
fetch was designed to only reject on network-level failures. HTTP errors are valid responses from the server's perspective.
Revisions (0)
No revisions yet.