Skip to content

    Frontend System Design

    Error Boundaries and Global Error Handling

    Learn what a React error boundary catches and misses, where to place boundaries, and how to report errors from render, events and promises without flooding.

    By Published 13 min read

    • frontend-system-design
    • error-boundaries
    • error-handling
    • react
    • reliability
    Share

    Standard lessonintermediateReact labFrontend System Design

    Before this: React's Render and Commit Phases

    What you'll learn: By the end of this lesson you will be able to say which errors a React error boundary catches and which it misses, place boundaries so one failing part does not take the page down, write a boundary as a small state machine with a retry budget and reset keys, send errors from render, events and promises to one reporter that does not flood, and test all of it without a browser.

    Think of the fuse box in a house. A fault in the kettle trips the kitchen circuit, not the whole house, and you can still turn on the lights while you fix it. A fault with no separate circuits takes everything down at once. A front end without error boundaries is the second house: one bad value in one corner of the page can leave the user a blank screen.

    The running example is a product page for a grocery marketplace (the front end of the ShopStream course project): a price block, a stock line, a reviews list and a "you may also like" strip, each filled from a different service.

    The core idea

    1. A thrown error is not the same as a failed request. The previous lesson, Error, Loading and Empty States, handled errors your data layer can see. This lesson handles the ones that are thrown: a component that throws while rendering, a handler that throws, a promise nobody handled.
    2. A boundary limits the blast radius. React unmounts what it cannot render; an error boundary decides how much that is and what to show in its place.
    3. Several channels, one reporter. Render errors, event errors and promise rejections arrive through different doors. A single reporter, with de-duplication, is where they meet.

    What a boundary is, and what it catches

    React's documentation defines an error boundary as a class component that defines static getDerivedStateFromError or componentDidCatch (or both). getDerivedStateFromError is called when a child, including a distant one, throws during rendering, and lets you show an error message instead of clearing the UI; it should be a pure function. componentDidCatch is where side effects belong, such as sending the error to a reporting service, and it receives an info object whose componentStack names the component that threw and its parents. React's documentation also says there is currently no way to write an error boundary as a function component.

    What a boundary does not catch is the part that surprises teams. The React documentation lists event handlers, server-side rendering, errors thrown in the boundary itself and asynchronous code such as setTimeout or requestAnimationFrame callbacks, with the exception of errors thrown inside a function passed to startTransition.

    Figure 1. Where each kind of error goes

    flowchart TD accTitle: Which mechanism sees which error accDescr: A decision tree. An error thrown while a component renders is caught by the nearest error boundary. An error thrown in an event handler or a timer callback goes to the window error event. A promise rejected with no handler fires unhandledrejection. If no boundary exists for a render error, React reports it as uncaught and the tree is unmounted. All of them can be sent to one reporter. A{"Where was it
    thrown?"} A -->|"while a component renders"| B["Nearest error boundary
    shows its fallback"] A -->|"event handler or
    timer callback"| C["window error event
    (boundary does not see it)"] A -->|"promise with no
    rejection handler"| D["window unhandledrejection
    event"] B --> R["One reporter"] C --> R D --> R

    How to read this: the first question is always where the error was thrown, because that decides which mechanism can see it. Only the first branch is a boundary's job. The other two need global listeners, or a deliberate hand-off into a render.

    Illustration 1: the minimal example

    The smallest useful boundary, with the reporting call kept out of the pure method:

    class ErrorBoundary extends Component<Props, { failed: boolean }> {
      state = { failed: false };
      static getDerivedStateFromError() {
        return { failed: true };            // pure: only picks the next state
      }
      componentDidCatch(error: unknown, info: ErrorInfo) {
        report(error, info.componentStack); // side effect lives here
      }
      render() {
        return this.state.failed ? this.props.fallback : this.props.children;
      }
    }

    Everything else is deciding where to put it, what the fallback says, when it may try again, and where the error goes.

    Global handlers

    Two events on window cover what a boundary cannot. MDN says the error event is fired when a resource failed to load or could not be used, for example when a script has an execution error, and that it is only generated for script errors thrown synchronously, such as during initial loading or inside event handlers. A promise rejected with no rejection handler fires unhandledrejection instead. For both, calling preventDefault() on the event stops the default console output.

    Two details matter for a reporter. A rejection can be any value, so a handler must cope with a string or undefined. And MDN notes that rejections from a cross-origin script do not fire unhandledrejection, because the event could leak data, so some failures never reach you this way.

    window.reportError() closes a loop. MDN describes it as a way to report errors to the console or to event handlers of the global scope, emulating an uncaught exception, so a library or your own code can deliver an error to the same error listener that real uncaught errors reach.

    React itself gives you a third door. The options of createRoot include onCaughtError, called when an error boundary catches an error, onUncaughtError, called when an error is thrown and not caught by any boundary, and onRecoverableError, called when React recovers by itself. Each receives the error and an errorInfo with the componentStack. By default React logs all errors to the console, and these three options are the documented place to plug in your own reporting.

    Figure 2. Three doors, one reporter

    Render, event and promise errors reaching one reporterRender error to Normalise (componentDidCatch); Event error to Normalise; Rejected promise to Normalise; Normalise to De-duplicate; De-duplicate to Reporting service (few sends)THE PAGERender error: caught by a boundaryRender errorcaught by aboundaryEvent error: window errorEvent errorwindow errorRejected promise: no handlerRejectedpromiseno handlerNormalise: any thrown valueNormaliseany thrown valueDe-duplicate: window and capDe-duplicatewindow and capReporting service: outside the pageReportingserviceoutside the pagecomponentDidCatchfew sends

    How to read this: three different mechanisms feed the two accent steps. Normalising comes first because the thrown value may be a string, null or an object; de-duplicating comes second so one broken component cannot flood the network. The reporting service itself is outside the page and outside this lesson.

    The boundary as a small state machine

    A boundary has two states, working and failed, and a few events. Writing it that way keeps the decisions out of the class, where they are hard to test, and in a pure function that a unit test can drive.

    Figure 3. Boundary states

    stateDiagram-v2 accTitle: States of an error boundary accDescr: The boundary starts in the ok state. A caught render error moves it to failed. From failed, pressing Try again moves it back to ok and counts one retry, if the error could be transient and the retry budget is not used up. A change in the reset keys moves it from failed to ok and sets the retry count back to zero. [*] --> ok ok --> failed: render error caught failed --> ok: Try again (retries left) failed --> ok: reset keys changed failed --> failed: no retries left, fallback stays

    How to read this: a retry is not free and not endless. Pressing Try again renders the children again; if they throw again the boundary returns to failed with one retry used. A changed input, such as another product id, is a new situation and starts the count again.

    Two rules sit on top. Offer Try again only when a retry could help: a lazy-loaded chunk that failed to download may load next time, while a TypeError from bad data will throw again with the same input. And cap the retries, so a permanent fault does not turn into a loop. Reset keys are the third tool: the boundary compares the values you give it on each update and clears its failure when any of them changes.

    One more rule: keep the fallback trivial. An error thrown inside the boundary itself is not caught by that boundary, so a fallback that does clever work can fail in the same moment.

    Getting errors that a boundary misses into one

    An event handler error can be sent to the nearest boundary on purpose by throwing it again during a render: call a state updater whose function throws. The lab wraps that in a small hook, and its tests show it works for handlers and for timer callbacks. It is a trade: you decide that this error should replace the part of the page with the fallback, which is right for "the component cannot continue" and wrong for "the purchase request failed", where the previous lesson's inline error is the better answer.

    Illustration 2: the realistic example

    On the product page, the "you may also like" strip renders item.name.toUpperCase() for each recommended item. One day the recommendation service returns an item with no name.

    • No boundary anywhere: the render throws. In the lab's run with no boundary, the whole root was empty afterwards and React reported the error as uncaught: the shopper sees a blank page, price and "Add to basket" included.
    • A boundary around the strip only: the strip shows its fallback (or nothing), the price and the reviews stay, and the reporter receives one error with a component stack.

    Figure 4. Placing boundaries

    Boundaries around independent parts of a product pagePage boundary to Price and basket; Page boundary to Reviews; Page boundary to Recs strip; Reviews to Reporter (caught); Recs strip to Reporter (caught)Page boundary: last resortPage boundarylast resortPrice and basket: no own boundaryPrice andbasketno own boundaryReviews: boundaryReviewsboundaryRecs strip: boundaryRecs stripboundaryReporter: one placeReporterone placecaughtcaught

    How to read this: the two accent boxes are optional parts with their own boundaries, so their failures stay local. The price and basket part has none of its own: a failure there should reach the page-level boundary, which shows a clear "this page cannot continue" message rather than a half-working basket.

    Illustration 3: the failure case, from the lab

    Three behaviours from the lab's tests (31 tests; React 19.3.1 under jsdom, development mode). Each is a place where a boundary alone is not the answer.

    1. A click handler that throws leaves the button on screen and does not trigger the fallback; the error arrived at the window error event in that run.
    2. A retry counter that resets on each failure never runs out. The first version of the lab's boundary rebuilt its state inside getDerivedStateFromError and lost the count; a test caught it.
    3. Rendering twice. React retried the failing component once more synchronously before showing the fallback, so a test that fails "on the first call" did not fail once. Render code must be pure and repeatable, the same property that React's Purity, StrictMode and Refs lesson explains.

    Trade-offs

    Choice Gain Cost
    One boundary at the root Never a blank page One failure replaces everything
    A boundary per independent part Failures stay local More fallbacks to design and test
    Retry button Recovers transient failures Useless, and noisy, for logic errors
    Reset keys Moving to another item recovers A bad input that changes often can loop
    Throw handler errors into a boundary One handling path Replaces UI that could have stayed
    Report every error Complete picture Floods the service and hides the new error

    Build it

    The lab is examples/frontend/labs/error-boundary-model (Node 26.13.1, React 19.3.1, Vitest 5.1.0). The pure core (src/core.ts) holds the error shape, the boundary reducer, the reporter and the global-handler installer; src/ErrorBoundary.tsx is the thin class. Run it from the example workspace.

    cd examples/frontend/labs/error-boundary-model
    pnpm test        # 31 tests (17 pure, 14 in jsdom)
    node src/demo.ts

    Expected output, captured from a real run (Node 26.13.1, node src/demo.ts, fake clock):

    1. normalizing what was thrown
       new TypeError('x is undefined') -> name=TypeError message="x is undefined"
       'plain string'                 -> name=NonError message="plain string"
       null                           -> name=NonError message="null was thrown"
       { code: 7 }                    -> name=NonError message="{\"code\":7}"
    2. reporter: dedupe window 1000 ms, at most 3 sends per window
       after 50 identical errors in 392 ms: sent=1 deduped=49
       after 4 distinct errors:             sent=3 deduped=49 dropped=2
       the same error after the window:     sent=4, record says suppressedBefore=49
    3. global handlers on an EventTarget (a stand-in for window)
       reported  global-error: script threw
       reported  unhandled-rejection: fetch promise rejected, nobody awaited it
       after uninstall: 2 reports in total (the third event was not reported)
    4. one boundary, maxRetries=2
       retryability: chunk load -> retry-may-help; TypeError -> retry-will-not-help
       start                                        status=ok     resets=0 tryAgainButton=false
       render throws (chunk failed to load)         status=failed resets=0 tryAgainButton=true
       Try again pressed, children render again     status=ok     resets=1 tryAgainButton=false
       throws again                                 status=failed resets=1 tryAgainButton=true
       second Try again, throws a third time        status=failed resets=2 tryAgainButton=false
       resetKeys changed (user opened another item) status=ok     resets=0 tryAgainButton=false

    Reading it: in section 2, fifty identical errors cost one send, and the next send after the window says it swallowed 49; distinct errors are capped at three per window. In section 4 the Try again button appears twice and then disappears, and a changed reset key starts the count again.

    What the lab does not show. It runs in jsdom, not a browser: it never saw a real window error event from a browser, a production build of React (the docs say a boundary-caught error does not bubble to window in production but does in development), server rendering or a screen. retryability is a toy rule (a name and a message pattern), not a classification you should copy.

    Break it. In src/core.ts, make canRetry ignore maxRetries. Two tests fail because the button never disappears. Restore it.

    In practice: a blank product page

    NOTE

    This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.

    The situation

    The product page has no error boundary. After a recommendations release, support reports white pages for a share of product views. The recommendation service sometimes returns an item with a missing field, and the strip's render throws.

    Starting architecture

    Figure 5. One tree, no boundary

    Starting architecture: one failing strip unmounts the whole pageRecs strip to Whole React tree (throw); Whole React tree to Blank pageRecs strip: throws on bad itemRecs stripthrows on baditemWhole React tree: no boundaryWhole Reacttreeno boundaryBlank page: price, basket, all goneBlank pageprice, basket,all gonethrow

    How to read this: red marks the failure and the amber box is where it is not stopped. With nothing to catch it, the error is reported as uncaught and the tree is gone.

    Options considered

    Option What it fixes What it costs Risk
    Validate the service's response The cause Contract work across teams Other bad data still throws somewhere
    One root boundary No more blank page A generic message for every failure A strip failure still hides the price
    A boundary per independent part, plus a root one The strip fails alone A fallback and a test per part A boundary added without a report hides the problem

    The decision

    Field Decision record
    Context A failure in an optional strip blanks the page and nobody is told why.
    Decision Put a boundary around each optional part (nothing as fallback) and one around the page body (a plain "This page cannot continue" with a link home). Send every caught error, and every global error and unhandledrejection, through one reporter with de-duplication. Offer Try again only for load failures, with a retry cap.
    Consequences, good A bad item hides one strip; support gets one report with a component stack instead of screenshots.
    Consequences, bad Silent fallbacks can hide a broken strip for weeks unless someone reads the reports.
    Revisit when Reports show many different errors from one part (then fix its data contract), or the page moves to server rendering.

    Rollout and verification

    1. Add the reporter first, with no boundaries, to see what already fails and how often.
    2. Add boundaries one part at a time, each with a test that throws inside it and checks that the siblings stay.
    3. Check the reports, not only the screen: one error per incident, with a component stack.
    4. Force each case by hand: a thrown render, a thrown click handler, a rejected promise nobody awaits.

    The 2 a.m. failure

    A new release throws inside a list row. The page now survives, but the reporting service is returning errors because every row, on every re-render, sends a report. The alert for the reporting quota fires.

    First three checks: (1) is one fingerprint repeating, or many different ones; (2) is the reporter de-duplicating; (3) did a boundary add a report on every retry. Mitigation: the reporter's window and cap keep the traffic bounded; the failing row's boundary stays in place. Follow-up: a test with fifty identical throws that expects one send.

    Architect's notes

    • Decide the blast radius first. For each part, ask "if this throws, what should still work?" and draw the boundary there.
    • A boundary without a report is a bug hider. The fallback is for the user; the report is for the team.
    • Normalise before you report. Anything can be thrown, so never assume error.message exists.
    • Keep fallbacks dumb. Plain text and a link; no data fetching, no components that can throw.

    Common mistakes

    • Expecting a boundary to catch a failed fetch or a click-handler error. It catches render errors, not those.
    • One boundary at the root and nothing else.
    • A "Try again" for errors a retry cannot fix.
    • Rebuilding state in getDerivedStateFromError, which drops the retry count.
    • Reporting every occurrence, so one fault floods the service.
    • Assuming the thrown value is an Error.

    Key takeaways

    • A boundary catches errors thrown while its children render; it misses event handlers, asynchronous callbacks, server rendering and itself.
    • Put boundaries around parts that can fail independently, and one last-resort boundary around the page.
    • Model the boundary as ok and failed, with a retry budget and reset keys; offer retry only when it can help.
    • Event errors go to window error, promise errors to unhandledrejection, caught render errors to componentDidCatch or onCaughtError; send all three to one reporter.
    • Normalise and de-duplicate before sending.
    • React may render a failing component more than once; keep render pure.

    Practice exercises

    Exercise 1: Starter (30 min). List the four kinds of error in this lesson (render, event handler, timer, rejected promise) and name, for each, which mechanism sees it.

    Exercise 2: Intermediate (2 hours). In the lab, add onRecoverableError to a createRoot call and route it through the reporter, with a test that it arrives with source render.

    Exercise 3: Advanced (half day). Add a severity to the error shape so "the page cannot continue" errors bypass the de-duplication window, and write the tests that show the trade-off.

    In this course:

    The next lessons in this module cover graceful degradation, resilient UI and client circuit breakers, and the failure modes of front-end systems; the observability module covers error reporting and source maps. They are named here in plain text because they are not published yet.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments