---
title: "Add a React error boundary and log the errors it misses"
description: "A React error boundary catches errors during render and shows a fallback. Here is the class, the errors it misses, and how to send each one to LogBrew, tested on React 19.3."
canonical: "https://logbrew.co/en/guides/react-error-boundary"
last_updated: "2026-11-21"
---

# Add a React error boundary and log the errors it misses

A React error boundary catches errors during render and shows a fallback. Here is the class, the errors it misses, and how to send each one to LogBrew, tested on React 19.3.

Tested on November 21, 2026 with React 19.3.1, Vite 8.3.8, Chrome 156, @logbrew/react 0.1.6, @logbrew/sdk 0.1.47, and logbrew CLI 0.1.96

By [Furkan Erday](https://github.com/furkanerday). Furkan Erday is the founder of LogBrew. He builds LogBrew with Claude Code and Codex every day.

Canonical: https://logbrew.co/en/guides/react-error-boundary

## Which React errors show a fallback and reach LogBrew

| Where the error was thrown | Fallback shown | Issue in LogBrew |
| --- | --- | --- |
| Render, inside `LogBrewErrorBoundary` | Yes | Yes |
| `useEffect`, inside the boundary | Yes | Yes |
| Render, with no boundary | No, empty root | Yes, from the root options |
| `onClick` handler | No | No |
| Async handler, after `await` | No | No |
| `onClick` with `captureReactError()` | No | Yes |

6 errors in 1 Vite production build with React 19.3.1 and @logbrew/react 0.1.6.

## Write an error boundary

### Write the boundary as a class component

React has no hook for this, so an error boundary is a class. `getDerivedStateFromError` switches it to the fallback on the next render. `componentDidCatch` gets the error and `info.componentStack`, the list of components above the one that threw.

```bash
import { Component } from "react";

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

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

  componentDidCatch(error, info) {
    console.log("caught:", error.message);
    console.log("in:", info.componentStack.split("\n")[1].trim());
  }

  render() {
    if (this.state.error) return <p role="alert">Could not load the taps.</p>;
    return this.props.children;
  }
}
```

### Wrap the part of the page that can fail

`TapList` reads `taps.map` when `taps` is missing, so it throws during render. The boundary showed `Could not load the taps.`, and the `Taproom` heading stayed. In development, React also printed the error with `The above error occurred in the <TapList> component`.

```bash
// TapList.jsx
export function TapList({ taps }) {
  return <ul>{taps.map((tap) => <li key={tap}>{tap}</li>)}</ul>;
}

// App.jsx
import { ErrorBoundary } from "./ErrorBoundary.jsx";
import { TapList } from "./TapList.jsx";

export function App() {
  return (
    <main>
      <h1>Taproom</h1>
      <ErrorBoundary>
        <TapList />
      </ErrorBoundary>
    </main>
  );
}
```

Output

```text
caught: Cannot read properties of undefined (reading 'map')
in: at TapList (http://127.0.0.1:25174/guide/TapList.jsx:3:27)
```

### An error in an event handler skips the boundary

React calls `onClick` outside of render, so the boundary never got the error. The button stayed on the page, and the browser printed an uncaught error. An error after `await` did the same.

```bash
export function PourButton() {
  return (
    <button onClick={() => { throw new Error("pour failed"); }}>Pour</button>
  );
}

// main.jsx
createRoot(document.getElementById("root")).render(
  <ErrorBoundary>
    <PourButton />
  </ErrorBoundary>
);
```

Output

```text
Uncaught Error: pour failed
    at onClick (http://127.0.0.1:25174/guide/PourButton.jsx:6:10)
```

### Pass a handler error to the boundary through state

Catch the error in the handler, store it with `setError`, and throw it in the next render. The boundary then shows its fallback and gets the error in `componentDidCatch`.

```bash
import { useState } from "react";

export function SafePourButton() {
  const [error, setError] = useState(null);
  if (error) throw error;

  function pour() {
    try {
      throw new Error("pour failed");
    } catch (caught) {
      setError(caught);
    }
  }

  return <button onClick={pour}>Pour</button>;
}
```

Output

```text
caught: pour failed
in: at SafePourButton (http://127.0.0.1:25174/guide/SafePourButton.jsx:7:28)
```

### With no boundary, React removes the whole tree

When no boundary catches a render error, React 19 unmounts the root. The `root` element was empty, and the heading was gone too. React printed the error and a warning that asks for an error boundary.

```bash
import { createRoot } from "react-dom/client";
import { TapList } from "./TapList.jsx";

createRoot(document.getElementById("root")).render(
  <main>
    <h1>Taproom</h1>
    <TapList />
  </main>
);
```

Output

```text
Uncaught TypeError: Cannot read properties of undefined (reading 'map')
An error occurred in the <TapList> component. Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://react.dev/link/error-boundaries to learn more about error boundaries.
```

## Send React errors to LogBrew

### Install the packages

`@logbrew/react` adds the provider, the error boundary, and the root options. Use a browser key of your LogBrew project as `clientKey`.

```bash
npm install @logbrew/sdk @logbrew/react react
```

### Create the client and a transport

The client keeps events in a queue until you call `client.flush(transport)`. The transport must return `{ statusCode }`. When ours returned the `fetch` response, the flush failed with `invalid transport response`. Set `VITE_LOGBREW_ENDPOINT` to `https://api.logbrew.co/v1/events`. We sent to a local LogBrew server.

```bash
import { createLogBrewReactClient } from "@logbrew/react";

export const client = createLogBrewReactClient({
  clientKey: import.meta.env.VITE_LOGBREW_CLIENT_KEY
});

export const transport = {
  async send(apiKey, body) {
    const response = await fetch(import.meta.env.VITE_LOGBREW_ENDPOINT, {
      method: "POST",
      headers: {
        authorization: `Bearer ${apiKey}`,
        "content-type": "application/json",
      },
      body
    });
    return { statusCode: response.status };
  }
};

export function send() {
  return client
    .flush(transport)
    .then((result) => console.log("sent", JSON.stringify(result)));
}
```

### Put LogBrewErrorBoundary inside LogBrewProvider

`LogBrewErrorBoundary` gets the client from `LogBrewProvider`. With no provider, it showed the fallback but sent nothing, and `onCaptureError` got `captureReactError requires a client`. `onError` runs after the capture, so flush there.

```bash
import { LogBrewErrorBoundary, LogBrewProvider } from "@logbrew/react";
import { client, send } from "./logbrew.js";
import { TapList } from "./TapList.jsx";

export function App() {
  return (
    <LogBrewProvider client={client}>
      <LogBrewErrorBoundary
        fallback={({ error, resetError }) => (
          <div role="alert">
            <p>Could not load the taps: {error.message}</p>
            <button onClick={resetError}>Try Again</button>
          </div>
        )}
        onError={send}
      >
        <TapList />
      </LogBrewErrorBoundary>
    </LogBrewProvider>
  );
}
```

Output

```text
sent {"statusCode":200,"attempts":1,"batches":1}
```

### Catch the errors that no boundary caught

`createLogBrewReactRootOptions()` gives `createRoot` its error callbacks. It recorded the render error with no boundary. It skips errors that `LogBrewErrorBoundary` already sent, so each error arrives 1 time.

```bash
import { createRoot } from "react-dom/client";
import { createLogBrewReactRootOptions } from "@logbrew/react";
import { client, send } from "./logbrew.js";
import { TapList } from "./TapList.jsx";

createRoot(
  document.getElementById("root"),
  createLogBrewReactRootOptions(client, { onUncaughtError: send })
).render(<TapList />);
```

Output

```text
sent {"statusCode":200,"attempts":1,"batches":1}
```

### Report handler errors with captureReactError()

No boundary and no root callback gets an error from a handler, so catch it and pass it to `captureReactError()`. The `metadata` you pass stays on the issue.

```bash
import { captureReactError } from "@logbrew/react";
import { client, send } from "./logbrew.js";

export function PayButton() {
  async function pay() {
    try {
      await Promise.resolve();
      throw new Error("payment declined");
    } catch (error) {
      captureReactError(client, error, { metadata: { action: "pay" } });
      send();
    }
  }

  return <button onClick={pay}>Pay</button>;
}
```

Output

```text
sent {"statusCode":200,"attempts":1,"batches":1}
```

### Read the issues back

We read the project with a read key. The render error inside the boundary and the same error with no boundary both came from `TapList.jsx`, so they became 1 issue with 2 occurrences. The handler error became an issue of its own.

```bash
logbrew issues --since 3h
```

Output

```text
Issues (2)
- 1613a62e-31a3-5045-a144-c9c593760bff unresolved error priority=medium React error: payment declined occurrences=1 users=unknown last_seen=2026-11-21T06:35:49.154Z service=unknown_service trace=2ca253b519dfa2866268889760e5f2a0 assignee=unassigned [unversioned / production]
- f9eb7448-fab2-5d52-82f3-592a3b680a08 unresolved error priority=medium React error: Cannot read properties of undefined (reading 'map') occurrences=2 users=unknown last_seen=2026-11-21T06:35:43.870Z service=unknown_service trace=225e883023acc9c768da676fedd8e2c1 assignee=unassigned [unversioned / production]
```

## What we saw when we tested it

We built 1 Vite app with React 19.3.1 and @logbrew/react 0.1.6, and ran each case in Chrome with a local LogBrew server. The outputs above come from the Vite dev server. We ran the same cases in a production build, and the results were the same.

Only errors during render and in `useEffect` reached a boundary. Errors in `onClick` and after `await` reached no boundary and no root callback. Only `captureReactError()` sent them.

|  | `LogBrewErrorBoundary` | `onUncaughtError` |
| --- | --- | --- |
| Render error inside the boundary | Yes | No |
| Render error with no boundary | No | Yes |
| Error in an event handler | No | No |

## Reset the boundary and try again

The fallback of `LogBrewErrorBoundary` gets `resetError`, which renders the children again. If the child throws again, the boundary shows the fallback again and sends 1 more event.

So fix the cause before the retry, for example load the data again. In our run, the retry rendered the list when the data was there.

|  | Fallback shown | Event sent |
| --- | --- | --- |
| First render error | Yes | Yes |
| `Try Again`, the child throws again | Yes | Yes |
| `Try Again`, the child renders | No | No |

## What LogBrew records

Each React error becomes an issue titled `React error:` and its message. The boundary records the mechanism `react.error_boundary` with `handled: true`. The root options record `react.uncaught_error` with `handled: false`.

LogBrew groups React errors by the error type and the file of the first stack frame. In our production build, 5 `Error` events with different messages, such as `keg sensor offline` and `tap list not loaded`, came from 1 bundle file and became 1 issue. In development, each component is a file of its own, so the issues stayed apart.

- `LogBrewErrorBoundary`
  - `mechanism`: `react.error_boundary`
  - `handled`: `true`
  - Issue: `React error: Cannot read properties of undefined (reading 'map')`
- `createLogBrewReactRootOptions()`
  - `mechanism`: `react.uncaught_error`
  - `handled`: `false`
  - Stack frames: 10
- `captureReactError()`
  - Issue: `React error: payment declined`
  - `metadata.action`: `pay`
  - Grouping key: `react.error:Error:…/HandlerButton.jsx`

## Questions people ask

### What is an error boundary in React?

A class component with `getDerivedStateFromError` or `componentDidCatch`. When a child throws during render, React shows the fallback of the boundary and keeps the rest of the page.

### Can I write an error boundary with hooks?

No. React has no hook for it, so the boundary is a class. Write it 1 time, or use `LogBrewErrorBoundary`, and put it around function components.

### Why does my error boundary not catch the error?

The error was thrown outside of render, often in an event handler or after `await`. Catch it there and report it with `captureReactError()`, or store it in state and throw it during render.

### Where should I put error boundaries?

Around each part of the page that can fail alone, such as a list that loads data, so the rest of the page stays. Put 1 near the root too, because an error that no boundary catches removes the whole tree.

### How do I log errors from an error boundary?

Send them from `componentDidCatch`, or use `LogBrewErrorBoundary` inside `LogBrewProvider`. Add `createLogBrewReactRootOptions()` to `createRoot` for the errors that no boundary caught.

## See every React error with its component stack

LogBrew records each React render error with its component stack, and groups the repeats into 1 issue. Start on the generous free tier, no card needed.

[Start Free](https://logbrew.co/en)

## Sources

- [React docs, Catching rendering errors with an Error Boundary](https://react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary)
- [React docs, createRoot parameters](https://react.dev/reference/react-dom/client/createRoot#parameters)
- [reactjs/react.dev#8157](https://github.com/reactjs/react.dev/issues/8157)

## More guides for agents, Python, Node.js, and React

- [Claude Code MCP and Codex MCP server setup](https://logbrew.co/en/guides/mcp-server-claude-code-codex)
- [Use AGENTS.md in Claude Code and Codex](https://logbrew.co/en/guides/agents-md)
- [Fix the Claude overloaded error 529 and rate limit error 429](https://logbrew.co/en/guides/claude-overloaded-rate-limit-error)
- [Set up Python logging with the right log levels and exception capture](https://logbrew.co/en/guides/python-logging)
- [Structured logging with a log format and log levels you can search by field](https://logbrew.co/en/guides/structured-logging)
- [Set up the Pino logger or Winston in Node.js and keep every error](https://logbrew.co/en/guides/node-logging)
- [Set up Django logging and keep the traceback of every 500 error](https://logbrew.co/en/guides/django-logging)
- [Set up FastAPI logging and handle errors without losing the traceback](https://logbrew.co/en/guides/fastapi-logging)
- [Trace ID vs span ID, decoded from a real traceparent header](https://logbrew.co/en/guides/trace-id)
- [Fix Minified React error #418 and #185 from the full message and your source line](https://logbrew.co/en/errors/minified-react-error)
- [How to fix errors and set up logs, traces, metrics & releases](https://logbrew.co/en/guides)
