Frontend System Design · Lesson 51 of 86 · 5 min
Handling API Errors in the Frontend
Interviewers use this to separate developers who just catch errors from engineers who design resilient systems.
After reading this, you'll be able to explain a full error handling strategy: from classifying the error, to deciding on a global or local response, to retrying intelligently, and finally, to logging it for debugging.
Classify Errors: The First Step
Not all errors are equal. Your first job is to figure out which kind you're dealing with. There are three broad categories.
Client Errors (4xx): The request itself is bad. 400 Bad Request for invalid data, 401 Unauthorized for missing credentials, 404 Not Found. These are the client's fault. The user or your code needs to fix something before trying again.
Server Errors (5xx): The request was valid, but the server failed. 500 Internal Server Error, 503 Service Unavailable. These are the server's fault. The client can't fix this; it can only wait or retry.
Network Errors: The request never reached the server, or the response never came back. The browser is offline, DNS fails, a proxy times out. This is nobody's fault, but you still have to handle it.
The trap: Treating all non-200 responses as a single failure type. The fetch API contributes to this confusion. A fetch promise only rejects on a network error. For a 404 or 500, the promise resolves successfully because a response was received. You must check response.ok to see if the HTTP status was in the 2xx range. Libraries like Axios throw on 4xx/5xx status codes by default, which simplifies this.
Global vs. Local Handling: The Core Trade-off
Once you've classified an error, you decide where to handle it. This is a core architectural decision.
Global handlers are for cross-cutting concerns. They live in one place, often in an API client wrapper or an Axios interceptor. Use them for errors that have a consistent, application-wide response.
- 401 Unauthorized: Redirect to the login page.
- 5xx Server Errors: Show a generic "Something went wrong" toast notification.
- Network Errors: Show an "You are offline" banner.
Local handlers are for context-specific feedback. They live inside the component or hook that initiated the API call, usually in a try...catch block. Use them for errors that the user can fix directly.
- 400 Bad Request on a form submission: Parse the response body for validation details and display error messages next to the invalid fields.
- 404 Not Found on a profile page: Render a "User not found" component instead of the profile.
In an interview, explaining this trade-off shows you think about architecture, not just code. A good system uses both: global handlers for consistency and boilerplate reduction, and local handlers for precise user feedback.
This Axios interceptor is a classic example of a global handler. It catches all responses, deals with common cases, and then re-throws the error so a local handler can still catch it if needed.
import axios, { AxiosError } from 'axios';
const api = axios.create({ baseURL: '/api' });
api.interceptors.response.use(
// On success, just return the response
(response) => response,
// On error, run this logic
(error: AxiosError) => {
if (!error.response) {
// Network error (no response received)
console.error('Network error:', error.message);
// showOfflineBanner();
return Promise.reject(error);
}
const { status } = error.response;
switch (status) {
case 401:
// Unauthorized: redirect to login
// window.location.href = '/login';
break;
case 500:
case 503:
// Server error: show a generic toast
// showGlobalErrorToast('Server is having issues. Please try again later.');
break;
}
// Re-throw the error to be caught by local handlers
return Promise.reject(error);
}
);
export default api;
Design a Predictable Error Payload
An HTTP status code tells you what happened, but the response body should tell you why. Without a consistent error structure, your frontend is left parsing random strings.
Work with your backend team to establish a standard error contract for all 4xx and 5xx responses. A good contract is simple and provides just enough information.
A minimal, effective error payload:
{
"message": "Invalid input provided.",
"code": "VALIDATION_ERROR",
"details": {
"email": "Email address is already in use.",
"password": "Password must be at least 8 characters long."
}
}
message: A user-facing summary.code: A stable, machine-readable identifier for the error type. Useful for programmatic decisions in the client.details: An optional object for field-specific validation errors. This is what you use to show errors next to form inputs.
Without this, you're forced to write brittle logic that breaks when a backend developer changes an error message.
When (and How) to Retry a Request
Retrying a failed request can make an application more resilient, but doing it wrong can make things worse.
Rule 1: Only retry transient errors. These are temporary problems that might resolve themselves. Network errors and some server errors (502 Bad Gateway, 503 Service Unavailable, 504 Gateway Timeout) are good candidates.
Rule 2: Never automatically retry client errors (4xx). The request is fundamentally flawed. Retrying a 400 Bad Request or 401 Unauthorized will just fail again and waste resources. The client must fix the request first.
When you do retry, use exponential backoff. Instead of retrying every second, increase the delay between attempts: 1s, 2s, 4s, 8s. This prevents your clients from overwhelming a struggling server (a "thundering herd" problem).
Finally, consider idempotency. An operation is idempotent if doing it multiple times has the same effect as doing it once. GET, PUT, and DELETE are typically idempotent. POST is not—retrying a POST to /users could create two users. Be very careful about retrying non-idempotent requests.
Don't Forget Observability
Showing the user a nice error message is only half the battle. You also need to know the error happened.
Your frontend application should send critical API errors to an observability platform (like Sentry, Datadog, or LogRocket). This allows your team to monitor application health, debug production issues, and be alerted to a spike in server errors.
When logging, include structured context:
- The HTTP status code and method.
- The request URL.
- A request or correlation ID, if you have one.
- The sanitized error response body.
This turns a user report of "it's broken" into an actionable bug report with a full stack trace and network context.
Try it
Using an API you know (like the GitHub API), write a small function that fetches a user's profile. Deliberately trigger a 404 by using a non-existent username and a 401 by omitting an auth token. Handle each case with a specific console.log message.
Next: We'll cover how you get those auth tokens in the first place in Authentication Flows: OAuth and JWT.
Lock it in — apply this lesson under interview conditions.