Frontend School
DashboardProblemsLearnPracticeMock InterviewReportsStatsBuy Credits
DashboardProblemsLearnPracticeMock Interview
Frontend System Design Roadmap
  1. 1.HTTP/1.1 vs HTTP/2 vs HTTP/3 (QUIC)
  2. 2.TCP and TLS Handshakes: Connection Setup Costs
  3. 3.Browser Network Stack and Connection Pooling
  4. 4.GET vs POST and Idempotency in HTTP
  5. 5.The Critical Rendering Path (CRP)
  6. 6.DOM, CSSOM and the Render Tree
  7. 7.Layout, Paint and Compositing
  8. 8.Reflows and Repaints Explained
  9. 9.Event Loop: Call Stack, Task and Microtask Queues
  10. 10.Async JavaScript: Promises and async/await
  11. 11.Web Workers: Multi-threading in the Browser
  12. 12.Browser Storage: Cookies, Web Storage, IndexedDB
  13. 13.Client-Side Storage: Limits and Security Risks
  14. 14.Choosing the Right Client-Side Storage
  15. 15.HTTP Caching: Cache-Control, ETag, Last-Modified
  16. 16.Browser-Level Caching Mechanisms
  17. 17.Cache Invalidation for Frontend Apps
  18. 18.Structuring a Large Single-Page App
  19. 19.Component-Based Architecture Principles
  20. 20.Props, State and Component Lifecycle
  21. 21.Module Bundling Basics
  22. 22.Core Web Vitals: LCP, INP and CLS
  23. 23.FCP and Time to Interactive (TTI) Explained
  24. 24.Measuring Performance: Lighthouse and WebPageTest
  25. 25.Asset Compression and Minification Basics
  26. 26.What Is a CDN and How Does It Work?
  27. 27.CDN Benefits: Latency, Availability, Offload
  28. 28.CDN Cache Behavior and Invalidation
  29. 29.Global State vs Local Component State
  30. 30.State Patterns: Redux, Zustand and Context
  31. 31.Data Fetching: React Query and SWR
  32. 32.Immutable Data in Frontend State
  33. 33.SSR vs CSR: Rendering Trade-offs
  34. 34.Hydration and Time to First Byte (TTFB)
  35. 35.Static Site Generation (SSG) for Speed and SEO
  36. 36.Incremental Static Regeneration (ISR)
  37. 37.Micro-Frontends: Core Principles
  38. 38.Micro-Frontend Integration Strategies
  39. 39.Communication Between Micro-Frontends
  40. 40.Micro-Frontends: Pros and Cons for Large Teams
  41. 41.Real-Time: Polling, SSE and WebSockets
  42. 42.Real-Time Use Cases: Chat, Alerts, Live Data
  43. 43.Designing a Real-Time Data Flow
  44. 44.Scaling WebSocket Connections
  45. 45.Responsive Images: srcset, sizes and picture
  46. 46.Modern Image Formats: WebP, AVIF, JPEG XL
  47. 47.Lazy Loading Images and Videos
  48. 48.Video Streaming: HLS, DASH, Adaptive Bitrate
  49. 49.REST and GraphQL for Frontend Engineers
  50. 50.Batching, Throttling and Debouncing API Calls
  51. 51.Handling API Errors in the Frontend
  52. 52.Authentication Flows: OAuth and JWT
  53. 53.Global Error Boundaries in React
  54. 54.Error Reporting: Sentry and LogRocket
  55. 55.Graceful Degradation and Fallback UIs
  56. 56.Real User Monitoring (RUM)
  57. 57.CORS: Cross-Origin Resource Sharing
  58. 58.Preventing XSS (Cross-Site Scripting)
  59. 59.CSRF Protection for Frontend Apps
  60. 60.Content Security Policy (CSP)
  61. 61.Storing Auth Tokens: Cookies vs localStorage
  62. 62.PWA Manifest and Installability
  63. 63.Service Workers: Lifecycle and Caching Strategies
  64. 64.Offline Support and Background Sync
  65. 65.Push Notifications for Web Apps
  66. 66.Webpack vs Vite vs Parcel
  67. 67.Code Splitting, Tree Shaking, Asset Optimization
  68. 68.Module Resolution and Hot Module Replacement
  69. 69.Monorepo Tooling: Nx and Lerna
  70. 70.Atomic Design for Component Libraries
  71. 71.Theming and Customization in Design Systems
  72. 72.Accessibility in Component Libraries
  73. 73.Component Library Docs, Testing and Versioning
  74. 74.Publishing and Consuming a Component Library
  75. 75.Full-Text Search: Levenshtein and Fuzzy Matching
  76. 76.Indexing Large Datasets in the Browser
  77. 77.Search Performance: Debouncing and Web Workers
  78. 78.Integrating Backend Search Services
  79. 79.Choosing a Chart Library: D3, Chart.js, Recharts
  80. 80.Rendering Large Datasets: Canvas vs SVG
  81. 81.Interactive, Responsive Data Visualizations
  82. 82.Data Fetching and Aggregation for Dashboards
  83. 83.A/B Test Design and Rollout Strategies
  84. 84.Client-Side vs Server-Side A/B Testing
  85. 85.Feature Flags and Remote Configuration
  86. 86.Experiment Data Collection and Analytics
Frontend System Design Roadmap
51

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.

Try a free mock interviewPractice system design problems
Previous

Batching, Throttling and Debouncing API Calls

Next

Authentication Flows: OAuth and JWT