Reliable Fetch API error handling starts with treating a request as a sequence of separate decisions: did the network operation finish, did the server return an acceptable HTTP status, can the response be parsed, and should the request be retried? This guide provides a reusable JavaScript pattern for status checks, JSON failures, timeouts, cancellation, retries, authentication errors, and user-facing fallback states.
Overview
The Fetch API does not reject its promise for every failed HTTP request. A response with a 404, 401, or 500 status normally resolves successfully at the JavaScript promise level. Fetch rejects when the request cannot be completed, such as when the browser reports a network failure, the request is aborted, or another problem prevents a response from being produced.
That distinction is the foundation of good Fetch API error handling. A production request should usually follow this order:
- Create a cancellation and timeout policy.
- Send the request with
fetch(). - Catch network errors and aborts.
- Check
response.okor the status code. - Parse the response deliberately and handle malformed or empty bodies.
- Retry only errors that are likely to succeed later.
- Map the final result to a useful UI state.
Keeping these stages separate makes failures easier to diagnose. It also prevents a common bug: displaying a success state because fetch() resolved even though the server returned an error response.
Checklist by scenario
1. Handle network failures and HTTP errors separately
Use a status check immediately after fetch(). The ok property is true for successful 2xx responses. For more specific behavior, inspect response.status or response.statusText.
async function getUser(userId, options = {}) {
const response = await fetch(`/api/users/${userId}`, {
signal: options.signal,
headers: { Accept: 'application/json' }
});
if (!response.ok) {
const error = new Error(`Request failed with status ${response.status}`);
error.status = response.status;
throw error;
}
return response.json();
}
try {
const user = await getUser('42');
renderUser(user);
} catch (error) {
showRequestError(error);
}
A network failure or abort is caught by the surrounding try...catch. An HTTP error is not, unless your code explicitly converts it into an exception as shown above.
2. Protect JSON parsing
A successful status does not guarantee valid JSON. An endpoint might return an empty body, HTML from a proxy, or a payload that does not match the expected schema. Parse the body inside the same error boundary and include enough context to diagnose the response without exposing sensitive data.
async function readJson(response) {
const contentType = response.headers.get('content-type') || '';
if (!contentType.includes('application/json')) {
throw new Error('Expected a JSON response');
}
try {
return await response.json();
} catch {
throw new Error('The server returned invalid JSON');
}
}
For endpoints where an empty successful response is valid, check the status first or read the body as text and parse only when it is non-empty. If the response contract matters to the application, validate required fields after parsing rather than assuming the JSON shape is correct.
3. Add a timeout with AbortController
Fetch has no universal application-level timeout that automatically matches your product needs. Use an AbortController to stop a request that has taken too long. A manual timer is explicit and works well in a reusable helper.
async function fetchWithTimeout(url, init = {}, timeoutMs = 8000) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
try {
return await fetch(url, {
...init,
signal: controller.signal
});
} finally {
clearTimeout(timer);
}
}
try {
const response = await fetchWithTimeout('/api/report');
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const report = await response.json();
} catch (error) {
if (error.name === 'AbortError') {
showMessage('The request took too long. Try again.');
} else {
showMessage('The report could not be loaded.');
}
}
If a caller already supplies a signal, decide whether the caller's cancellation and the timeout should work together. In modern environments, signal-combining and timeout helpers may be available, but check the runtime support required by your application before relying on them. A manual controller remains a clear fallback.
4. Cancel stale requests
Cancellation is different from failure. In a search box, a request for an old query may finish after a newer request and overwrite the correct results. Keep the current controller and abort it before starting the next request.
let activeController;
async function search(query) {
activeController?.abort();
activeController = new AbortController();
try {
const response = await fetch(`/api/search?q=${encodeURIComponent(query)}`, {
signal: activeController.signal
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return await response.json();
} catch (error) {
if (error.name === 'AbortError') return null;
throw error;
}
}
Do not show a generic error for an intentional cancellation. Treat it as a neutral outcome unless the user explicitly needs cancellation feedback.
5. Retry only transient failures
A retry can help with a temporary network interruption or a server-side failure, but it cannot fix invalid input, missing permissions, or a malformed request. Retry conservatively, limit attempts, and use increasing delays with jitter so multiple clients do not retry at exactly the same time.
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
async function fetchWithRetry(url, init = {}, options = {}) {
const attempts = options.attempts ?? 3;
const baseDelay = options.baseDelay ?? 300;
for (let attempt = 0; attempt < attempts; attempt += 1) {
try {
const response = await fetch(url, init);
const retryableStatus =
response.status === 408 ||
response.status === 429 ||
response.status >= 500;
if (response.ok || !retryableStatus || attempt === attempts - 1) {
return response;
}
} catch (error) {
if (init.signal?.aborted || attempt === attempts - 1) throw error;
}
const jitter = Math.random() * 100;
await sleep(baseDelay * 2 ** attempt + jitter);
}
throw new Error('Request failed after retries');
}
Only retry operations that are safe to repeat, such as a read or an idempotent update. Be careful with payments, order creation, or any operation that can produce a duplicate side effect. When the server supplies a Retry-After header, follow the API's documented policy rather than applying an aggressive client-side loop.
6. Give authentication errors their own path
A 401 usually means the credentials are missing, expired, or invalid; a 403 commonly indicates that the authenticated user is not allowed to perform the operation. Do not retry either status indefinitely. Instead, refresh credentials through the application's defined flow, send the user to sign in when appropriate, or show an authorization message.
When debugging token-based requests, inspect claims and expiry carefully without logging secrets. The JWT debugging guide provides a focused workflow for tracing authentication failures.
What to double-check
- Request method and body: Set the correct method, serialize JSON with
JSON.stringify(), and send the matchingContent-Typeheader. - CORS behavior: A browser may block a cross-origin request before your code can inspect a response. Verify the server's origin and preflight configuration rather than treating every such failure as an API status error.
- Response content: Confirm whether the endpoint returns JSON, text, a file, or no body. Choose
json(),text(),blob(), or no parser accordingly. - Cancellation ownership: Make clear whether a component, route, user action, or timeout owns the signal. Avoid treating deliberate unmount cancellation as a server outage.
- Request identity: For search, filtering, or rapidly changing views, prevent an older response from replacing newer state even when cancellation is not immediate.
- API contract: Keep client expectations aligned with the endpoint schema. An OpenAPI validation workflow can help detect mismatches between requests and responses.
- Accessible fallback states: Expose loading, error, empty, and retry states in the interface. Preserve focus and provide a clear action, especially when a form submission fails.
Common mistakes
Assuming fetch() rejects on a 404. Always check response.ok or the status code before parsing or rendering success.
Retrying every exception. A bad URL, a validation error, a permission failure, or a user cancellation is not fixed by repeated requests. Classify the error first.
Retrying non-idempotent operations automatically. A repeated POST may create duplicate records. Use an idempotency design supported by the API when a write must be safely retried.
Leaving timers active. Clear timeout timers in a finally block so completed requests do not leave unnecessary callbacks behind.
Showing raw server messages to users. Server responses can be incomplete, technical, or unsafe to display directly. Log structured diagnostic information carefully and present a concise, actionable message.
Logging tokens or full response bodies. Authentication headers, personal data, and sensitive payloads should not appear in routine browser or server logs.
When to revisit
Revisit this Fetch API error-handling checklist whenever you add an endpoint, change authentication, introduce a new runtime or browser support target, or move a request into a shared data layer. It is also worth reviewing before a release that changes retry behavior, timeout values, caching, or user-facing loading states.
Use this short review before merging a request integration:
- Confirm that network failures, aborts, HTTP errors, and parse failures produce distinguishable internal outcomes.
- Confirm that timeout values match the operation and that every timer is cleaned up.
- Confirm that only safe, transient failures are retried and that attempts are capped.
- Confirm that authentication failures do not trigger an endless retry loop.
- Test empty, malformed, slow, offline, unauthorized, forbidden, rate-limited, and server-error responses.
- Check that the interface offers a useful fallback and remains understandable with keyboard and assistive technology.
For broader API work, pair this pattern with a structured REST API authentication workflow and keep request and response contracts documented. Treat error handling as part of the endpoint integration itself, not as a final wrapper added after the successful path is complete.