debugjavascriptMajor
Network Error Types: TypeError vs HTTP Error vs AbortError
Viewed 0 times
fetch errortypeerrorhttp erroraborterrorres.okstatus check
Error Messages
Problem
Error handling code catches all fetch errors the same way, missing critical distinctions between connectivity failures, server errors, and cancelled requests.
Solution
Fetch rejects its promise only for network-level failures (TypeError). HTTP errors (4xx, 5xx) resolve normally — you must check
res.ok or res.status manually.async function safeFetch(url, options) {
let res;
try {
res = await fetch(url, options);
} catch (err) {
if (err.name === 'AbortError') throw new CancelledError();
// TypeError: network failure, DNS error, SSL error
throw new NetworkError(err.message);
}
if (!res.ok) {
const body = await res.text();
throw new HttpError(res.status, res.statusText, body);
}
return res;
}
class HttpError extends Error {
constructor(status, statusText, body) {
super(`HTTP ${status}: ${statusText}`);
this.status = status;
this.body = body;
}
}Why
Fetch's design means
fetch('/bad-url') and fetch('/returns-404') behave very differently. A 404 resolves successfully — only network-level failures reject. This trips up almost every developer using fetch for the first time.Gotchas
- CORS failures surface as TypeErrors, not HTTP errors — you get no status code information.
res.okis true for 200-299 only — not 3xx.- Always consume the response body on error: uncollected body streams can cause connection leaks.
Revisions (0)
No revisions yet.