Skip to content
jshacks.dev
Patterns

Error Boundaries as a Design Pattern

An error boundary contains a failure to one part of a program so the rest keeps working. See React error boundaries in React 19 and the idea in plain code.

7 min read
Summarize in AI
Flat illustration of a log with a failing line and a wrench, with the JavaScript, React and Vite logos.

An error boundary is a wrapper that catches failures from the code inside it, shows a fallback in place of the broken part and lets the rest of the program carry on. The idea is older than React and larger than user interfaces: any system made of independent parts, such as plugins, widgets, jobs or request handlers, benefits from containing a failure at the edge of the part that failed. This post shows the pattern first in plain JavaScript, then as React error boundaries in React 19, covering what they catch and what they do not, how to reset them, where to place them and how to report what they catch.

The problem: one failure takes everything down

Imagine a dashboard made of widgets. One widget throws while rendering because its data is malformed.

dashboard.mjsJavaScript
const widgets = [
  () => "Sales: 120",
  () => {
    throw new Error("cannot read 'total' of undefined");
  },
  () => "Users: 45",
];

function renderDashboard() {
  return widgets.map((widget) => widget()).join(" | ");
}

try {
  console.log(renderDashboard());
} catch (err) {
  console.log(`dashboard failed: ${err.message}`);
}
Text
dashboard failed: cannot read 'total' of undefined

Two healthy widgets were lost because of one broken one. The user sees nothing where they could have seen most of the page. The error crossed every boundary between the widget and the top of the program, because there were no boundaries.

The pattern in plain JavaScript

A boundary is a function that runs a unit of work, catches whatever it throws and returns a fallback.

boundary.mjsJavaScript
function boundary(render, fallback, report = () => {}) {
  try {
    return render();
  } catch (err) {
    report(err);
    return fallback(err);
  }
}

const reported = [];
const widgets = [
  () => "Sales: 120",
  () => {
    throw new Error("cannot read 'total' of undefined");
  },
  () => "Users: 45",
];

const page = widgets
  .map((widget, i) =>
    boundary(
      widget,
      () => `[widget ${i + 1} unavailable]`,
      (err) => reported.push(err.message),
    ),
  )
  .join(" | ");

console.log(page);
console.log(reported);
Text
Sales: 120 | [widget 2 unavailable] | Users: 45
[ "cannot read 'total' of undefined" ]

The broken widget was replaced with a placeholder, and the other two rendered. The error was reported separately, so someone can fix it. This is the whole pattern: isolate, replace, report. Three questions decide how well it works: how large is each boundary, what does the fallback show and how does a boundary recover.

React error boundaries

React renders components as a tree, and an error thrown while rendering unmounts the whole tree by default. An error boundary is a component that catches errors from its descendants during rendering. It has to be a class component, because React exposes the hooks for catching errors only as class lifecycle methods: static getDerivedStateFromError to switch to the fallback, and componentDidCatch to run side effects such as reporting.

ErrorBoundary.jsxJSX
import { Component } from "react";

export class ErrorBoundary extends Component {
  state = { hasError: false };

  static getDerivedStateFromError() {
    return { hasError: true };
  }

  componentDidCatch(error, info) {
    this.props.onError?.(error, info.componentStack);
  }

  render() {
    if (this.state.hasError) return this.props.fallback;
    return this.props.children;
  }
}

console.log(ErrorBoundary.getDerivedStateFromError(new Error("boom")));
Text
{ hasError: true }

getDerivedStateFromError runs during rendering and must be pure: it returns the state that makes the next render show the fallback. componentDidCatch runs after the fallback is committed, so it is the place for logging and error reporting. Usage wraps the parts that may fail.

usage.jsxJSX
import { ErrorBoundary } from "./ErrorBoundary.jsx";

export function Dashboard() {
  return (
    <main>
      <ErrorBoundary fallback={<p>Sales unavailable</p>}>
        <SalesWidget />
      </ErrorBoundary>
      <ErrorBoundary fallback={<p>Users unavailable</p>}>
        <UsersWidget />
      </ErrorBoundary>
    </main>
  );
}

If SalesWidget throws while rendering, only its boundary switches to the fallback. UsersWidget keeps working, and so does the rest of the page. Without the boundaries, the whole Dashboard would unmount, and in a production build the user would see a blank page.

What error boundaries do not catch

Knowing the gaps matters as much as knowing the feature. React's documentation lists what a boundary cannot catch.

  • Event handlers. An error in an onClick function is not a rendering error, so the boundary does not see it. Use a try and catch in the handler.

  • Asynchronous code. Errors in setTimeout, fetch callbacks and promises that are not part of rendering are outside the boundary.

  • Server-side rendering. Boundaries do not catch errors on the server in the same way. The server render handles errors through its own options.

  • Errors in the boundary itself. If the fallback or the boundary's own render throws, the error goes to the next boundary up.

A common workaround for asynchronous errors is to store the error in state and throw it during render, which routes it to the nearest boundary.

async-to-boundary.jsxJSX
import { useState } from "react";

export function useAsyncError() {
  const [, setState] = useState();
  return (error) =>
    setState(() => {
      throw error;
    });
}

A component calls const throwError = useAsyncError() and passes caught errors to it. The state updater function throws during React's next render, so the boundary above catches it. This is a deliberate trick, and the react-error-boundary package offers a ready-made version as its useErrorBoundary hook.

Recovering: resetting a boundary

A boundary that stays on its fallback forever is a dead end. Offer a way back: a retry button, or automatic reset when something changes, such as the data the component displays.

Resettable.jsxJSX
import { Component } from "react";

export class ResettableBoundary extends Component {
  state = { error: null };

  static getDerivedStateFromError(error) {
    return { error };
  }

  componentDidUpdate(prevProps) {
    if (this.state.error && prevProps.resetKey !== this.props.resetKey) {
      this.setState({ error: null });
    }
  }

  render() {
    if (this.state.error) {
      return (
        <div role="alert">
          <p>Something went wrong.</p>
          <button onClick={() => this.setState({ error: null })}>Try again</button>
        </div>
      );
    }
    return this.props.children;
  }
}

Passing a resetKey, such as the current record id, resets the boundary when the user navigates to a different item, so one bad record does not leave the whole page stuck. The retry button clears the error and tries rendering the children again, which helps when the cause was transient. If the underlying problem persists, the error returns immediately, so do not reset in a loop automatically.

Where to put boundaries

Placement is a design decision with a trade-off. One boundary at the root is a safety net that replaces a crashed app with a message, and it loses everything on the screen. A boundary around every component is noisy, and the fallbacks multiply. A good layout uses three levels:

  • Root. A last resort, showing a general failure page with a reload option.

  • Route or page. A broken page does not break navigation, so the user can go elsewhere.

  • Independent widgets. Parts of a page that can fail separately, like a comments panel, a recommendation list or an embedded chart, each get a boundary and a small fallback.

Place a boundary around code you trust less: third-party components, user-generated content renderers and anything fed by data from an API. Do not wrap code in a boundary to hide a bug you should fix. The boundary limits the damage, and the report is how you learn about the problem.

Reporting what was caught

A boundary that swallows errors silently is worse than none, because failures become invisible. Report from componentDidCatch, or from the root options in React 19, which expose callbacks for the different situations.

root-options.jsxJSX
import { createRoot } from "react-dom/client";

const root = createRoot(document.getElementById("root"), {
  onCaughtError(error, info) {
    reportError({ kind: "caught", error, stack: info.componentStack });
  },
  onUncaughtError(error, info) {
    reportError({ kind: "uncaught", error, stack: info.componentStack });
  },
  onRecoverableError(error) {
    reportError({ kind: "recoverable", error });
  },
});

React 19 added onCaughtError and onUncaughtError to createRoot and hydrateRoot: the first runs for errors a boundary caught, and the second for errors no boundary caught. Together they give one central place to send errors to a monitoring service, with the component stack attached, instead of reporting from every boundary. reportError here stands for your own reporting function.

The pattern beyond React

The same shape appears wherever independent parts share a process.

  • Plugin hosts run each plugin's hooks inside a try and catch, so one faulty plugin does not stop the application.

  • Request handlers have an error middleware at the edge, so one failing request becomes a 500 response and does not crash the server.

  • Job runners catch errors per job, mark that job failed and continue with the queue.

  • Workers and processes are boundaries of their own: a crash in a worker thread or child process is contained by the operating system, and the parent can restart it. The Erlang tradition calls this supervision, and it is the same idea at the process level.

In each case, the design questions are the same: size the boundary to the unit that can fail independently, give it a fallback that is honest about what happened, report the error and offer recovery.

Testing

Test that the boundary shows its fallback and reports the error. In a DOM test environment with a component that throws, you render inside the boundary and assert on the fallback. The plain-JavaScript version tests directly.

boundary.test.mjsJavaScript
import assert from "node:assert/strict";
import { test } from "node:test";

test("boundary returns the fallback and reports the error", () => {
  const reported = [];
  const result = boundary(
    () => {
      throw new Error("bad data");
    },
    (err) => `fallback: ${err.message}`,
    (err) => reported.push(err.message),
  );
  assert.equal(result, "fallback: bad data");
  assert.deepEqual(reported, ["bad data"]);
});

test("boundary passes through a successful result", () => {
  assert.equal(boundary(() => "fine", () => "never"), "fine");
});
Text
✔ boundary returns the fallback and reports the error (0.9ms)
✔ boundary passes through a successful result (0.2ms)
ℹ tests 2
ℹ pass 2
ℹ fail 0

When boundaries are the wrong tool

A boundary hides a failure from the user, and sometimes the failure should stop the program. If a payment step fails, showing a friendly fallback in its place and continuing could lead the user to think the payment worked. Use boundaries for display and for optional features, where a missing piece is acceptable, and let critical flows fail visibly.

Also inFrameworks
Share

Keep reading

Flat illustration of two options weighed side by side, with the JavaScript, Vite and Node.js logos.
Functions

Classes vs Factory Functions

Classes vs factory functions in JavaScript compared on private state, this, instanceof, inheritance, memory, JSON and testing, with exact output.

7 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.