---
title: "Aggiungi un boundary di errore React e registra gli errori che si lascia sfuggire"
description: "Un boundary di errore React intercetta gli errori durante il render e mostra un fallback. Ecco la classe, gli errori che si lascia sfuggire e come inviare ciascuno a LogBrew, provati su React 19.3."
canonical: "https://logbrew.co/it/guides/react-error-boundary"
last_updated: "2026-11-21"
---

# Aggiungi un boundary di errore React e registra gli errori che si lascia sfuggire

Un boundary di errore React intercetta gli errori durante il render e mostra un fallback. Ecco la classe, gli errori che si lascia sfuggire e come inviare ciascuno a LogBrew, provati su React 19.3.

Testato il 21 novembre 2026 con React 19.3.1, Vite 8.3.8, Chrome 156, @logbrew/react 0.1.6, @logbrew/sdk 0.1.47 e logbrew CLI 0.1.96

Di [Furkan Erday](https://github.com/furkanerday). Furkan Erday è il fondatore di LogBrew. Sviluppa LogBrew ogni giorno con Claude Code e Codex.

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

## Quali errori React mostrano un fallback e arrivano a LogBrew

| Dove è stato lanciato l’errore | Fallback mostrato | Problema in LogBrew |
| --- | --- | --- |
| Render, dentro `LogBrewErrorBoundary` | Sì | Sì |
| `useEffect`, dentro il boundary | Sì | Sì |
| Render, senza boundary | No, radice vuota | Sì, con le opzioni della radice |
| Handler `onClick` | No | No |
| Handler async, dopo `await` | No | No |
| `onClick` con `captureReactError()` | No | Sì |

6 errori in 1 build di produzione Vite con React 19.3.1 e @logbrew/react 0.1.6.

## Scrivi un boundary di errore

### Scrivi il boundary come componente di classe

React non ha un hook per questo, quindi un boundary di errore è una classe. `getDerivedStateFromError` lo fa passare al fallback al render successivo. `componentDidCatch` riceve l’errore e `info.componentStack`, la lista dei componenti sopra quello che ha lanciato l’errore.

```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;
  }
}
```

### Avvolgi la parte della pagina che può fallire

`TapList` legge `taps.map` quando manca `taps`, quindi lancia un errore durante il render. Il boundary ha mostrato `Could not load the taps.`, e il titolo `Taproom` è rimasto. In sviluppo, React ha anche stampato l’errore con `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)
```

### Un errore in un gestore di eventi salta il boundary

React chiama `onClick` fuori dal render, quindi il boundary non ha mai ricevuto l’errore. Il pulsante è rimasto sulla pagina, e il browser ha stampato un errore non intercettato. Un errore dopo `await` ha fatto lo stesso.

```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)
```

### Passa l’errore di un handler al boundary tramite lo state

Intercetta l’errore nell’handler, salvalo con `setError` e lancialo al render successivo. Il boundary allora mostra il suo fallback e riceve l’errore 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)
```

### Senza boundary, React rimuove tutto l’albero

Quando nessun boundary intercetta un errore di render, React 19 smonta la radice. L’elemento `root` era vuoto, e anche il titolo era sparito. React ha stampato l’errore e un avviso che chiede un boundary di errore.

```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.
```

## Invia gli errori React a LogBrew

### Installa i pacchetti

`@logbrew/react` aggiunge il provider, il boundary di errore e le opzioni della radice. Usa una chiave browser del tuo progetto LogBrew come `clientKey`.

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

### Crea il client e un transport

Il client tiene gli eventi in coda finché non chiami `client.flush(transport)`. Il transport deve restituire `{ statusCode }`. Quando il nostro ha restituito la risposta di `fetch`, il flush è fallito con `invalid transport response`. Imposta `VITE_LOGBREW_ENDPOINT` su `https://api.logbrew.co/v1/events`. Noi abbiamo inviato a un server LogBrew locale.

```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)));
}
```

### Metti LogBrewErrorBoundary dentro LogBrewProvider

`LogBrewErrorBoundary` prende il client da `LogBrewProvider`. Senza provider, ha mostrato il fallback ma non ha inviato niente, e `onCaptureError` ha ricevuto `captureReactError requires a client`. `onError` gira dopo la cattura, quindi fai il flush lì.

```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}
```

### Intercetta gli errori che nessun boundary ha intercettato

`createLogBrewReactRootOptions()` dà a `createRoot` le sue callback di errore. Ha registrato l’errore di render senza boundary. Salta gli errori che `LogBrewErrorBoundary` ha già inviato, quindi ogni errore arriva 1 sola volta.

```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}
```

### Segnala gli errori degli handler con captureReactError()

Né un boundary né una callback della radice ricevono l’errore di un handler, quindi intercettalo e passalo a `captureReactError()`. I `metadata` che passi restano sul problema.

```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}
```

### Rileggi i problemi

Abbiamo letto il progetto con una chiave di lettura. L’errore di render dentro il boundary e lo stesso errore senza boundary venivano entrambi da `TapList.jsx`, quindi sono diventati 1 problema con 2 occorrenze. L’errore dell’handler è diventato un problema a parte.

```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]
```

## Cosa abbiamo visto nei test

Abbiamo creato 1 app Vite con React 19.3.1 e @logbrew/react 0.1.6, ed eseguito ogni caso in Chrome con un server LogBrew locale. Gli output qui sopra vengono dal server di sviluppo di Vite. Abbiamo eseguito gli stessi casi in una build di produzione, con gli stessi risultati.

Solo gli errori durante il render e in `useEffect` hanno raggiunto un boundary. Gli errori in `onClick` e dopo `await` non hanno raggiunto né un boundary né una callback della radice. Solo `captureReactError()` li ha inviati.

|  | `LogBrewErrorBoundary` | `onUncaughtError` |
| --- | --- | --- |
| Errore di render dentro il boundary | Sì | No |
| Errore di render senza boundary | No | Sì |
| Errore in un gestore di eventi | No | No |

## Reimposta il boundary e riprova

Il fallback di `LogBrewErrorBoundary` riceve `resetError`, che esegue di nuovo il render dei figli. Se il figlio lancia di nuovo l’errore, il boundary mostra di nuovo il fallback e invia 1 evento in più.

Quindi correggi la causa prima di riprovare, per esempio ricarica i dati. Nel nostro test, il nuovo tentativo ha mostrato la lista quando i dati c’erano.

|  | Fallback mostrato | Evento inviato |
| --- | --- | --- |
| Primo errore di render | Sì | Sì |
| `Try Again`, il figlio fallisce ancora | Sì | Sì |
| `Try Again`, il figlio viene mostrato | No | No |

## Cosa registra LogBrew

Ogni errore React diventa un problema intitolato `React error:` seguito dal messaggio. Il boundary registra il meccanismo `react.error_boundary` con `handled: true`. Le opzioni della radice registrano `react.uncaught_error` con `handled: false`.

LogBrew raggruppa gli errori React per tipo di errore e per file del primo frame dello stack. Nella nostra build di produzione, 5 eventi `Error` con messaggi diversi, come `keg sensor offline` e `tap list not loaded`, venivano da 1 file del bundle e sono diventati 1 problema. In sviluppo ogni componente è un file a sé, quindi i problemi sono rimasti separati.

- `LogBrewErrorBoundary`
  - `mechanism`: `react.error_boundary`
  - `handled`: `true`
  - Problema: `React error: Cannot read properties of undefined (reading 'map')`
- `createLogBrewReactRootOptions()`
  - `mechanism`: `react.uncaught_error`
  - `handled`: `false`
  - Frame dello stack: 10
- `captureReactError()`
  - Problema: `React error: payment declined`
  - `metadata.action`: `pay`
  - Chiave di raggruppamento: `react.error:Error:…/HandlerButton.jsx`

## Domande frequenti

### Cos’è un boundary di errore in React?

Un componente di classe con `getDerivedStateFromError` o `componentDidCatch`. Quando un figlio lancia un errore durante il render, React mostra il fallback del boundary e mantiene il resto della pagina.

### Posso scrivere un boundary di errore con gli hook?

No. React non ha un hook per questo, quindi il boundary è una classe. Scrivilo 1 volta, oppure usa `LogBrewErrorBoundary`, e mettilo intorno ai componenti funzione.

### Perché il mio boundary di errore non intercetta l’errore?

L’errore è stato lanciato fuori dal render, spesso in un gestore di eventi o dopo `await`. Intercettalo lì e segnalalo con `captureReactError()`, oppure salvalo nello state e lancialo durante il render.

### Dove metto i boundary di errore?

Intorno a ogni parte della pagina che può fallire da sola, come una lista che carica dati, così il resto della pagina resta. Mettine anche 1 vicino alla radice, perché un errore che nessun boundary intercetta rimuove tutto l’albero.

### Come registro gli errori di un boundary di errore?

Inviali da `componentDidCatch`, oppure usa `LogBrewErrorBoundary` dentro `LogBrewProvider`. Aggiungi `createLogBrewReactRootOptions()` a `createRoot` per gli errori che nessun boundary ha intercettato.

## Vedi ogni errore React con il suo stack di componenti

LogBrew registra ogni errore di render React con il suo stack di componenti e raggruppa le ripetizioni in 1 problema. Inizia con il generoso piano gratuito, senza carta.

[Inizia gratis](https://logbrew.co/it)

## Fonti

- [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)

## Altre guide per gli agenti, Python, Node.js e React

- [Aggiungi un server MCP a Claude Code e Codex](https://logbrew.co/it/guides/mcp-server-claude-code-codex)
- [Usa AGENTS.md in Claude Code e Codex](https://logbrew.co/it/guides/agents-md)
- [Risolvi l’errore overloaded 529 e l’errore di rate limit 429 di Claude](https://logbrew.co/it/guides/claude-overloaded-rate-limit-error)
- [Configura il modulo Python logging con i livelli di log giusti e la cattura delle eccezioni](https://logbrew.co/it/guides/python-logging)
- [Structured logging con un formato dei log e livelli che puoi cercare per campo](https://logbrew.co/it/guides/structured-logging)
- [Configura il logging in Node.js con Pino o Winston senza perdere nessun errore](https://logbrew.co/it/guides/node-logging)
- [Configura il logging di Django e conserva lo stack trace di ogni errore 500](https://logbrew.co/it/guides/django-logging)
- [Configura il logging di FastAPI e gestisci gli errori senza perdere lo stack trace](https://logbrew.co/it/guides/fastapi-logging)
- [ID traccia vs ID span, decodificati da un vero header traceparent](https://logbrew.co/it/guides/trace-id)
- [Risolvi l’errore Minified React #418 e #185 con il messaggio completo e la tua riga di codice](https://logbrew.co/it/errors/minified-react-error)
- [Guide su errori, log, tracce, metriche e release](https://logbrew.co/it/guides)
