Error Handling
Handling HTTP errors, network failures, timeout, and parsing error responses
Skills taught: api.http-error-handling, api.network-error, api.error-parsing, api.retry-logic
Robust API error handling
// ── Typed error class for API errors ──
class ApiError extends Error {
constructor(status, body) {
super(body?.message || body?.error || `HTTP ${status}`);
this.status = status;
this.body = body;
this.name = 'ApiError';
}
}
// ── Robust fetch wrapper ──
async function apiFetch(url, options = {}) {
let res;
try {
res = await fetch(url, {
signal: AbortSignal.timeout(10_000), // 10s timeout
...options,
});
} catch (err) {
// Network error: no internet, DNS fail, timeout, request aborted
if (err.name === 'AbortError' || err.name === 'TimeoutError') {
throw new Error('Request timed out — check your connection');
}
throw new Error('Network error — you may be offline');
}
if (!res.ok) {
// Try to parse error body (may be JSON or HTML)
const body = await res.json().catch(() => null);
throw new ApiError(res.status, body);
}
if (res.status === 204) return null; // No Content
return res.json();
}
// ── Retry with exponential backoff ──
async function fetchWithRetry(url, options = {}, maxRetries = 3) {
const RETRYABLE = new Set([429, 500, 502, 503, 504]);
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await apiFetch(url, options);
} catch (err) {
const isLast = attempt === maxRetries;
const status = err.status;
// Only retry specific error types
if (err.name !== 'ApiError' || !RETRYABLE.has(status) || isLast) {
throw err;
}
// For 429, respect Retry-After header if present
// Otherwise: exponential backoff + jitter
const backoff = Math.pow(2, attempt - 1) * 1000 + Math.random() * 200;
console.warn(`Attempt ${attempt} failed (${status}). Retrying in ${backoff.toFixed(0)}ms...`);
await new Promise(r => setTimeout(r, backoff));
}
}
}
// ── Usage with error handling ──
try {
const user = await fetchWithRetry('/api/users/42');
console.log('User:', user.name);
} catch (err) {
if (err instanceof ApiError) {
switch (err.status) {
case 401: redirect('/login'); break;
case 403: showMessage('You do not have permission'); break;
case 404: showMessage('User not found'); break;
case 422: showValidationErrors(err.body.errors); break;
case 429: showMessage('Too many requests — please wait'); break;
default: showMessage('Server error — try again later');
}
} else {
showMessage(err.message); // network/timeout error
}
}
Frequently Asked Questions
How do I show the user a helpful error message instead of 'HTTP 422'?
Parse the error body from the API response — most APIs return a structured JSON error: `{ "error": "VALIDATION_FAILED", "message": "Email is invalid" }`. After checking `!res.ok`, do `const errBody = await res.json().catch(() => null)`. Then use `errBody?.message || res.statusText` as the user-facing message. For 422 Validation errors, many APIs also return a list of field-specific errors — render those next to the relevant form fields.