Error Handling: HTTP Status Codes
Map HTTP status codes to user-facing messages, distinguish between network errors and server errors, and implement retry logic.
Error Handling: HTTP Status Codes is a free Frontend Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Frontend Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
HTTP Status Code Categories
Status codes are grouped by first digit: 2xx success, 3xx redirect, 4xx client error (your fault), 5xx server error (their fault).
Common 2xx Codes
200 OK: success with body. 201 Created: resource created (often returns the new resource). 204 No Content: success with no body (DELETE, sometimes PUT).
Common 4xx Codes
400 Bad Request: malformed input. 401 Unauthorized: missing/invalid auth. 403 Forbidden: authenticated but not allowed. 404 Not Found: resource doesn't exist. 409 Conflict: state conflict (duplicate email). 422 Unprocessable Entity: validation failed.
Common 5xx Codes
500 Internal Server Error: generic server fault. 502 Bad Gateway: upstream service failed. 503 Service Unavailable: server overloaded or down. 504 Gateway Timeout: upstream didn't respond in time.
Mapping Codes to User Messages
Translate status codes into useful UI messages — never show 'Error 500' to a user.
function userMessage(status) {
if (status === 401) return 'Please sign in to continue.';
if (status === 403) return "You don't have permission for that.";
if (status === 404) return 'Not found.';
if (status === 409) return 'Already exists.';
if (status === 422) return 'Please check the form for errors.';
if (status >= 500) return 'Something went wrong. Try again in a moment.';
return 'Something unexpected happened.';
}Network Errors vs Server Errors
A failed fetch (offline, DNS failure, CORS) is different from a server error response. Network errors throw; server errors return a Response with status >= 400.
try {
const res = await fetch('/api/users');
if (!res.ok) {
// Server replied but with error status
throw new Error(`Server error ${res.status}`);
}
return res.json();
} catch (err) {
if (err instanceof TypeError) {
// Network failure — fetch couldn't reach server
throw new Error('Network error. Check your connection.');
}
throw err;
}Retry Logic for 5xx and Network Errors
Server errors and network failures are often transient. Retry with exponential backoff.
async function fetchWithRetry(url, options, maxRetries = 3) {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
const res = await fetch(url, options);
if (res.ok || (res.status >= 400 && res.status < 500)) return res;
// 5xx — retryable
} catch (err) {
if (attempt === maxRetries - 1) throw err;
}
await new Promise(r => setTimeout(r, 2 ** attempt * 1000)); // 1s, 2s, 4s
}
}Don't Retry 4xx
4xx errors are your fault — retrying won't help. Only retry 5xx and network failures. The exception is 429 (Too Many Requests), which often includes a Retry-After header.
Reading the Retry-After Header
Servers may include Retry-After on 429 and 503 — wait that many seconds before retrying.
const res = await fetch('/api/limited');
if (res.status === 429) {
const after = parseInt(res.headers.get('Retry-After') || '5', 10);
await new Promise(r => setTimeout(r, after * 1000));
return fetch('/api/limited');
}Surface Validation Errors
422 responses typically include a JSON body listing field errors. Render them next to the relevant form input.
// Server response for 422:
// { errors: { email: 'Already taken', password: 'Too short' } }
if (res.status === 422) {
const { errors } = await res.json();
Object.entries(errors).forEach(([field, msg]) => {
setFieldError(field, msg);
});
}Telemetry: Log Errors to a Service
Send errors to Sentry, Datadog, or LogRocket so you can see them in production. Include request URL, method, status, and a sanitised body (no secrets).
Show Actionable Recovery
Every error UI should offer the user a way forward: a retry button, a link to support, a way back to a working page. Dead-end error screens frustrate users.
Quick Check
An API returns a 422 Unprocessable Entity. What does this typically mean?
Recap: HTTP Error Handling
2xx success, 3xx redirect, 4xx client error, 5xx server error. Map codes to user-friendly messages. Distinguish network errors (TypeError from fetch) from server errors (res.ok false). Retry 5xx and network failures with exponential backoff; never retry 4xx (except 429 with Retry-After). Surface 422 field errors. Log errors to a service like Sentry.
Frequently asked questions
Is the “Error Handling: HTTP Status Codes” lesson free?
Yes — the full text of “Error Handling: HTTP Status Codes” is free to read here on the web, and the Frontend Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Frontend Academy course, upgrade to CoddyKit PRO.
What will I learn in “Error Handling: HTTP Status Codes”?
Map HTTP status codes to user-facing messages, distinguish between network errors and server errors, and implement retry logic. You practise Frontend Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Frontend Academy?
No prior experience is required. Frontend Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Error Handling: HTTP Status Codes” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Frontend Academy lesson?
Yes. Every Frontend Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Fetch API: GET POST PUT DELETE
- Axios: Interceptors and Base URL
- Error Handling: HTTP Status Codes
- SWR and React Query for Data Caching