← Back to React, page 5

react-0089 · Hard senior

How would you design error handling for a large React application, covering error boundaries, root error callbacks in React 19, async errors and monitoring?

Layer it. Put error boundaries at several levels (app, route, widget) so a failure removes only a small part of the screen and offers a retry. Use the React 19 root options onCaughtError, onUncaughtError and onRecoverableError to report to monitoring in one place. Boundaries do not catch event handler or async errors, so handle those with try/catch and state, or rethrow into render. Send errors with release, route and user context, and test the fallback paths.

Full answer

Error boundaries (class components with getDerivedStateFromError, or the react-error-boundary library) catch errors thrown while rendering, in lifecycle methods and in constructors of their children. They do not catch errors in event handlers, in async code such as promises and timers, in server rendering, or in the boundary itself.

Layering. A root boundary guards against a white screen and shows a generic page. Route-level boundaries keep the navigation working when one page fails. Widget-level boundaries isolate risky or third-party parts such as charts or embeds. Each fallback explains what happened and offers a retry, which resets the boundary (a resetKey prop, or a key change) and re-renders the children.

Reporting in React 19. createRoot and hydrateRoot accept onCaughtError (errors caught by a boundary), onUncaughtError (errors that no boundary caught) and onRecoverableError (for example hydration mismatches that React repaired). React 19 no longer logs the same error three times. These callbacks are the single place to send errors and the component stack to Sentry or a similar service. The boundary's own componentDidCatch remains useful for local actions.

Async and event errors. In handlers use try/catch, set an error state and show an inline message. To let a boundary handle an async failure, store the error in state and throw it during render, if (error) throw error, or use a data library whose throwOnError option does that. Suspense plus use surfaces rejected promises to the nearest boundary.

Operational practice: attach release version, route, user id (as policy allows) and feature flags to reports, deduplicate noisy errors, set alerts on error rate per release, and upload source maps. Test failure paths: a component test that makes a child throw, and an end-to-end test that simulates API failure. Avoid swallowing errors silently.

The example shows a boundary with a reset, and the root callbacks capturing the error.

jsx
import { Component, useState } from 'react';
import { createRoot } from 'react-dom/client';

class Boundary extends Component {
  state = { error: null };

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

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

function Chart({ data }) {
  if (!data) throw new Error('No chart data');
  return <p>Chart with {data.length} points</p>;
}

function Page() {
  const [data, setData] = useState(null);
  return (
    <main>
      <h1>Dashboard</h1>
      <Boundary>
        <Chart data={data} />
      </Boundary>
      <button onClick={() => setData([1, 2, 3])}>Load data</button>
    </main>
  );
}

const reports = [];
const container = document.getElementById('root');
const root = createRoot(container, {
  onCaughtError(error, info) {
    reports.push('caught by a boundary: ' + error.message + ' (component stack present: ' + Boolean(info.componentStack) + ')');
  },
  onUncaughtError(error) {
    reports.push('uncaught: ' + error.message);
  },
});

root.render(<Page />);
await new Promise((resolve) => setTimeout(resolve, 30));
console.log('after first render: ' + container.querySelector('[role=alert] p').textContent);

[...container.querySelectorAll('button')].find((b) => b.textContent === 'Load data').click();
await new Promise((resolve) => setTimeout(resolve, 30));
[...container.querySelectorAll('button')].find((b) => b.textContent === 'Try again').click();
await new Promise((resolve) => setTimeout(resolve, 30));
console.log('after loading data and retrying: ' + container.querySelector('p').textContent);
console.log('reports: ' + JSON.stringify(reports));
root.unmount();

This ran as a script. The Chart throws until data exists, the boundary shows the fallback, and Load data followed by Try again recovers. The root callback recorded the error once. Output of the run: after first render: Something went wrong: No chart data after loading data and retrying: Chart with 3 points reports: ["caught by a boundary: No chart data (component stack present: true)"]

Key points

  • Layer boundaries at app, route and widget level, each with a retry.
  • Boundaries miss event handlers, async code and server rendering errors.
  • React 19 root options onCaughtError, onUncaughtError and onRecoverableError centralize reporting.
  • Rethrow async errors in render or use a library option so a boundary can handle them.
  • Include release, route and context in reports and test failure paths.

Common mistakes

  • Expecting error boundaries to catch errors in event handlers or promises.
  • One boundary at the root only, so any widget failure blanks the app.
  • A retry button that re-renders without fixing the cause and loops.
  • Logging errors without release or route context.
  • Swallowing errors in catch blocks without reporting.

Follow-ups

  • How do you reset a boundary when the route changes?
  • How would you let a boundary catch a failed fetch?
  • Which errors would you report and which would you ignore?

Tips

  • Mention what boundaries do not catch. It is the usual follow-up.
  • Know the React 19 root callbacks. They are a recent change.
  • Describe operational practice, not only the component.