# Add Error Boundaries to a React App

Yes. An agent adds a reusable error boundary to a React app at the root and around each private route, with a styled fallback, a retry and a test, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-error-boundaries/react/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads how the app is mounted before it decides where a boundary goes. In an app shaped like cypress-io/cypress-realworld-app, `package.json` pins `react` 18.2.0, `react-router-dom` 5.3.4, `@mui/material` 5, `xstate` 4.38.3 with `@xstate/react`, `formik` and `vite`. `src/index.tsx` renders `App` inside a `Router` with a custom `history`, a `StyledEngineProvider` and a `ThemeProvider`. `src/containers/App.tsx` reads the `authService` machine and, when logged in, renders `PrivateRoutesContainer`, which puts `MainLayout` around a `Switch` of `PrivateRoute` entries for transactions, user settings, notifications, bank accounts, transaction creation, transaction detail and onboarding. `TransactionDetailContainer` reads `first(transactionDetailState.context?.results)` from its machine and renders from it. A `grep` for `componentDidCatch`, `getDerivedStateFromError` and `react-error-boundary` finds nothing: an exception in any render unmounts the whole tree to a blank page, and the `AlertBar` driven by `snackbarMachine` never gets to say what happened.

React 18 has no hook for this, so the agent writes a class. `src/components/ErrorBoundary.tsx` implements `getDerivedStateFromError` and `componentDidCatch`, takes an optional `onError` callback and a `resetKey`, and renders a fallback built from the MUI pieces the app already uses: a `Container` with a `Typography` message, a `Try again` `Button` that clears the state, and a `Reload` button that calls `window.location.reload()`. The fallback carries `data-test="error-boundary"` attributes in the convention every component in `src/components` follows, so a test can find it. When `resetKey` changes, the boundary clears itself, which is how a navigation away from a broken page recovers without a reload.

Two placements. `src/index.tsx` wraps `App` in one boundary inside the `ThemeProvider`, so the fallback is styled, and that boundary's `onError` logs through `console.error` because nothing else exists above the machines. `PrivateRoutesContainer.tsx` wraps the children of each `PrivateRoute` in a second boundary with `resetKey` set to the route path and `onError` sending `SHOW` with severity `error` to the `snackbarService` it already receives as a prop, so a crash in the transaction detail page shows the fallback in the content area while `MainLayout`, the `NavBar` and the drawer keep working. The sign-in and sign-up routes in `App.tsx` sit under the root boundary only.

The test is a Cypress component test, because that is how this repository tests components: `src/components/ErrorBoundary.cy.tsx` joins the four existing `*.cy.tsx` files under the `specPattern` in `cypress.config.ts`. It mounts the boundary around a child that throws on first render, asserts the fallback's `data-test` elements, clicks `Try again` with the child fixed, and asserts the child rendered; a second case checks `onError` was called with the thrown error. The run then does what the `install` job in `.github/workflows/main.yml` does: `yarn types`, `yarn lint`, `yarn test:unit:ci` and `yarn build:ci`, plus `yarn cypress:run:component` for the new spec.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add error boundaries to this React app and open a pull request that links the Linear issue. Read package.json, vite.config.ts, cypress.config.ts, src/index.tsx, src/containers/App.tsx, src/containers/PrivateRoutesContainer.tsx, src/components/PrivateRoute.tsx, src/components/MainLayout.tsx, src/components/AlertBar.tsx, src/machines/snackbarMachine.ts and one existing *.cy.tsx component test first. Write src/components/ErrorBoundary.tsx as a class with getDerivedStateFromError and componentDidCatch, an onError prop, a resetKey prop that clears the state when it changes, and a MUI fallback with Try again and Reload buttons carrying data-test attributes. Wrap App in src/index.tsx inside the ThemeProvider, and wrap each PrivateRoute's children in PrivateRoutesContainer.tsx with resetKey set to the route path and onError sending SHOW with severity error to snackbarService. Do not change the machines or the routes. Add src/components/ErrorBoundary.cy.tsx covering the fallback, the retry and the onError call. Run yarn types, yarn lint, yarn test:unit:ci, yarn build:ci and yarn cypress:run:component, and paste the component test output in the pull request.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request that adds `src/components/ErrorBoundary.tsx` and `src/components/ErrorBoundary.cy.tsx`, and edits `src/index.tsx` and `src/containers/PrivateRoutesContainer.tsx`. The machines, routes and `MainLayout` are unchanged. It links the Linear issue, and its description shows the Cypress component run with the new spec and the `vite build` summary.

On a repository with this `Cypress Tests` workflow the pull request runs the type check, lint, unit tests and build in the `install` job, then the end-to-end specs across five parallel Chrome containers. Those specs sign in and walk every private route, and they pass because a boundary that never catches renders its children unchanged.

A reviewer checks that the route-level boundary resets on navigation, that the snackbar message does not include a stack trace, and that the root fallback still looks right without `MainLayout` around it. Then they merge and move the issue.

## Run it on every Linear issue labelled agent

In the Project for this repository, add an automation with a Linear trigger on `linear.issue.labeled` filtered to the `agent` label and this prompt. The trigger adds the issue after the prompt; it fills in no placeholder. Each labelled issue starts its own run in its own sandbox and opens its own pull request on the repository, under the automation's `max_runs_per_hour` cap.

Without an automation, a handler on your server can receive Linear's webhook, put the issue text into `input`, and POST to `/o/{org}/sessions` with the repository in `resources`. A `run.completed` webhook on the API key then carries the `session_url` to read the pull request from.

## Why run it on Rush?

A boundary is only proven by a component that throws, and nobody keeps one of those in the app. In a Rush sandbox the agent mounts the boundary around a throwing child with Cypress component testing, the tool this repository already uses for components, clicks the retry, and keeps the run's output in its record, so the pull request shows the fallback and the recovery rather than describing them.

This app's checks need a Cypress browser image, a built bundle and five parallel containers, which is more than a laptop runs for a two-file change. Each run on Rush does the type check, lint, build and component run in its own sandbox, and the same automation handles every labelled issue.

## Frequently asked questions

### Why a class component?

React 18 exposes `getDerivedStateFromError` and `componentDidCatch` only on classes; there is no hook. The class is small and the rest of the app stays functional. The `react-error-boundary` package wraps the same class and is used if the prompt asks for it.

### Will it catch errors in event handlers or fetches?

No. Boundaries catch errors thrown during render, in lifecycle methods and in constructors below them. A failed request inside an XState machine goes to that machine's error state as today, and the pull request says so.

### How does a broken page recover?

Each route boundary takes the route path as `resetKey`, so navigating to another page clears it, and the fallback's `Try again` clears it in place. `Reload` is the last resort and calls `window.location.reload()`.

### Does this change the end-to-end tests?

No. The e2e specs under `cypress/tests/ui` walk the same routes, and a boundary with nothing to catch renders its children unchanged. The new coverage is one component spec that mounts the boundary with a throwing child.

## More React jobs

- [Add i18n to a React App from a Linear Issue](https://getrush.ai/run/add-i18n/react/)
- [Add Optimistic Updates to a React App](https://getrush.ai/run/add-optimistic-ui/react/)
- [Convert React Class Components to Hooks](https://getrush.ai/run/convert-class-components-to-hooks/react/)

## The same job on other stacks

- [Add Error Boundaries to a React Router App](https://getrush.ai/run/add-error-boundaries/react-router/)
- [Add Error Boundaries to a SolidJS App](https://getrush.ai/run/add-error-boundaries/solidjs/)
- [Add Error Boundaries to a Vue App](https://getrush.ai/run/add-error-boundaries/vue/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
