Cursor rule for React error boundaries covering what they catch, a typed class boundary, react-error-boundary use, feature-level placement, reset and monitoring.
.cursor/rules/react-error-boundaries.mdc. Downloaded files need to be placed in that repository path.---
description: "Cursor rule for React error boundaries covering what they catch, a typed class boundary, react-error-boundary use, feature-level placement, reset and monitoring."
globs: "**/*"
alwaysApply: false
---
# React Error Boundaries
Applies to: React client UI where a rendering error in one part of the tree must not blank the whole page, and to error reporting for those failures.
Version baseline: checked against the React 19 docs. Error boundaries are still class components; React has no built-in hook for them. Read `react` and any `react-error-boundary` version in `package.json`. In Next.js App Router projects, prefer the framework's `error.tsx` / `global-error.tsx` files (see the end).
## What boundaries catch, and what they do not
- They catch errors thrown while rendering, in lifecycle methods and in constructors of components below them, and errors in transitions (`startTransition`).
- They do NOT catch errors in event handlers, in async code (`setTimeout`, promise callbacks after `await`), during server rendering, or inside the boundary itself. Handle those with `try/catch` and error state. To send an async error to the nearest boundary, rethrow it during render through a state update:
```tsx
const [, setCrash] = useState<null>(null);
// inside a catch block of an async handler:
setCrash(() => { throw error; });
```
## A reusable boundary
```tsx
import { Component, type ErrorInfo, type ReactNode } from "react";
type Props = {
fallback: (args: { error: Error; reset: () => void }) => ReactNode;
onError?: (error: Error, info: ErrorInfo) => void;
children: ReactNode;
};
type State = { error: Error | null };
export class ErrorBoundary extends Component<Props, State> {
state: State = { error: null };
static getDerivedStateFromError(error: Error): State {
return { error };
}
componentDidCatch(error: Error, info: ErrorInfo) {
this.props.onError?.(error, info); // send to the monitoring service with info.componentStack
}
reset = () => this.setState({ error: null });
render() {
const { error } = this.state;
return error ? this.props.fallback({ error, reset: this.reset }) : this.props.children;
}
}
```
- `getDerivedStateFromError` renders the fallback, and `componentDidCatch` reports the error. Do not set state in `componentDidCatch` for the fallback.
- If the project already uses the `react-error-boundary` package, use its `ErrorBoundary` (`fallbackRender`, `onError`, `resetKeys`) and its `useErrorBoundary().showBoundary(error)` for async errors instead of writing your own. That hook comes from the package, not from React.
## Placement
- Put boundaries around independent features (a widget, a sidebar, a route's main content), so one failure keeps the rest of the page usable. Add one top-level boundary as the last resort.
- Do not wrap every small component. Too many boundaries hide failures and produce fragmented fallbacks.
## Fallback UI and recovery
- Fallbacks say what failed in plain language, keep surrounding navigation available, and offer a recovery action: "Try again" calls `reset`, or a link leads somewhere safe.
- Retrying re-renders the same children. If the error depends on input (a bad id, stale data), reset with a `key` change, or with `resetKeys` in react-error-boundary, when that input changes.
- Do not show stack traces or raw error messages to end users in production.
## Logging and monitoring
- Report from `componentDidCatch` / `onError`, including `info.componentStack`. React 19 also offers root-level hooks: `createRoot(el, { onCaughtError, onUncaughtError, onRecoverableError })` for central reporting.
- Use the project's monitoring SDK (Sentry, Datadog, etc.). Do not add a new vendor without asking.
## Next.js App Router note
`app/**/error.tsx` (must be a Client Component) wraps that route segment's page in a boundary. In Next.js 16.3+ it receives `error` and `retry` (re-fetches and re-renders). Use `global-error.tsx` for errors in the root layout. For component-level boundaries inside Next.js, prefer `catchError` from `next/error`, which does not swallow `redirect()` and `notFound()`.
## Verify before finishing
- Write a test that renders a child that throws, and asserts that the fallback appears, `onError` is called once, and "Try again" recovers when the child stops throwing (React Testing Library). Expect React to log the caught error in tests. Silence it with a scoped `console.error` spy, not globally.
- Manually trigger an error in development and confirm the rest of the page still works and the error reaches monitoring.
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.
Cursor
frontend
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
A dashboard crashes to a blank page when one widget throws during render, and the developer asks Cursor to contain the failure and report it.
In Dashboard.tsx, wrap RevenueChart, ActivityFeed and the sidebar so a failure in one keeps the others visible. Report errors with our existing reportError(error, componentStack). The feed's 'Load more' button fetches data in an onClick handler. React 19.2, no react-error-boundary.
Illustrative; not a recorded model run. A typed class ErrorBoundary (getDerivedStateFromError for the fallback, componentDidCatch calling reportError with info.componentStack). Each widget is wrapped separately, with a fallback that names the widget and offers 'Try again', which resets the boundary. The answer explains that the onClick fetch error is not caught by boundaries; it is handled with try/catch and error state, or rethrown via setState(() => { throw error }). The test makes a child throw and asserts the fallback, a single report call and recovery.Cursor applies project rules stored as .mdc files in .cursor/rules. Each rule's frontmatter (description, globs, alwaysApply) decides whether it is always included, attached to matching files, chosen by the agent from its description, or only used when you @-mention it. Cursor also reads AGENTS.md in the project root and subdirectories for plain-Markdown instructions.
.cursor/rules/react-error-boundaries.mdcStarting point, not a tested configuration for your repository. Attached when files matching the globs are in context (alwaysApply: false with globs). Review the instructions, adapt the file paths and run your project's existing checks.
---
description: "React Error Boundaries: Placement, Fallbacks, Recovery and Error Reporting project conventions"
globs: "**/*"
alwaysApply: false
---
# React Error Boundaries
Applies to: React client UI where a rendering error in one part of the tree must not blank the whole page, and to error reporting for those failures.
Version baseline: checked against the React 19 docs. Error boundaries are still class components; React has no built-in hook for them. Read `react` and any `react-error-boundary` version in `package.json`. In Next.js App Router projects, prefer the framework's `error.tsx` / `global-error.tsx` files (see the end).
## What boundaries catch, and what they do not
- They catch errors thrown while rendering, in lifecycle methods and in constructors of components below them, and errors in transitions (`startTransition`).
- They do NOT catch errors in event handlers, in async code (`setTimeout`, promise callbacks after `await`), during server rendering, or inside the boundary itself. Handle those with `try/catch` and error state. To send an async error to the nearest boundary, rethrow it during render through a state update:
```tsx
const [, setCrash] = useState<null>(null);
// inside a catch block of an async handler:
setCrash(() => { throw error; });
```
## A reusable boundary
```tsx
import { Component, type ErrorInfo, type ReactNode } from "react";
type Props = {
fallback: (args: { error: Error; reset: () => void }) => ReactNode;
onError?: (error: Error, info: ErrorInfo) => void;
children: ReactNode;
};
type State = { error: Error | null };
export class ErrorBoundary extends Component<Props, State> {
state: State = { error: null };
static getDerivedStateFromError(error: Error): State {
return { error };
}
componentDidCatch(error: Error, info: ErrorInfo) {
this.props.onError?.(error, info); // send to the monitoring service with info.componentStack
}
reset = () => this.setState({ error: null });
render() {
const { error } = this.state;
return error ? this.props.fallback({ error, reset: this.reset }) : this.props.children;
}
}
```
- `getDerivedStateFromError` renders the fallback, and `componentDidCatch` reports the error. Do not set state in `componentDidCatch` for the fallback.
- If the project already uses the `react-error-boundary` package, use its `ErrorBoundary` (`fallbackRender`, `onError`, `resetKeys`) and its `useErrorBoundary().showBoundary(error)` for async errors instead of writing your own. That hook comes from the package, not from React.
## Placement
- Put boundaries around independent features (a widget, a sidebar, a route's main content), so one failure keeps the rest of the page usable. Add one top-level boundary as the last resort.
- Do not wrap every small component. Too many boundaries hide failures and produce fragmented fallbacks.
## Fallback UI and recovery
- Fallbacks say what failed in plain language, keep surrounding navigation available, and offer a recovery action: "Try again" calls `reset`, or a link leads somewhere safe.
- Retrying re-renders the same children. If the error depends on input (a bad id, stale data), reset with a `key` change, or with `resetKeys` in react-error-boundary, when that input changes.
- Do not show stack traces or raw error messages to end users in production.
## Logging and monitoring
- Report from `componentDidCatch` / `onError`, including `info.componentStack`. React 19 also offers root-level hooks: `createRoot(el, { onCaughtError, onUncaughtError, onRecoverableError })` for central reporting.
- Use the project's monitoring SDK (Sentry, Datadog, etc.). Do not add a new vendor without asking.
## Next.js App Router note
`app/**/error.tsx` (must be a Client Component) wraps that route segment's page in a boundary. In Next.js 16.3+ it receives `error` and `retry` (re-fetches and re-renders). Use `global-error.tsx` for errors in the root layout. For component-level boundaries inside Next.js, prefer `catchError` from `next/error`, which does not swallow `redirect()` and `notFound()`.
## Verify before finishing
- Write a test that renders a child that throws, and asserts that the fallback appears, `onError` is called once, and "Try again" recovers when the child stops throwing (React Testing Library). Expect React to log the caught error in tests. Silence it with a scoped `console.error` spy, not globally.
- Manually trigger an error in development and confirm the rest of the page still works and the error reaches monitoring.
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Cursor's docs recommend keeping individual rules under 500 lines and splitting large rules into composable ones. Cursor's documentation states that it supports AGENTS.md in the project root and in subdirectories. Use AGENTS.md for plain-Markdown instructions you also want other tools to read, and .mdc rules when you need Cursor's scoping options (globs, description-based selection, always-apply).
Documentation checked 2026-11-05: Cursor docs: Rules
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.