Sub topic 12
onCaughtError and onUncaughtError at the Root
This chapter assumes you can write a class-based error boundary, know which errors boundaries do not catch, and have used createRoot from react-dom/client. It also assumes you are on React 19 or later, where these callbacks are available.
Why report errors at the root
Earlier chapters showed componentDidCatch, which reports errors from one boundary. That approach has two gaps in a real application.
- You must remember to add reporting code to every boundary you write. A boundary from a library, or one added by a teammate in a hurry, may log nothing.
- Some render errors are not caught by any boundary. Without a boundary, React unmounts the whole tree, and no
componentDidCatchever runs.
React 19 closes both gaps with options on createRoot (and on hydrateRoot). They give you one central place to see every error React handles for that root.
The three root callbacks
createRoot accepts an options object with three error callbacks.
| Option | When React calls it |
|---|---|
| `onCaughtError` | An error boundary caught an error. |
| `onUncaughtError` | An error was thrown and no boundary caught it. |
| `onRecoverableError` | React recovered from an error on its own, for example a hydration mismatch it could repair. |
This chapter focuses on the first two. onRecoverableError is mostly relevant to server rendering and hydration, so it only gets a short mention at the end.
Each of the first two callbacks receives two arguments.
error: the value that was thrown. This is usually anError, but JavaScript allows throwing any value, so do not assumeerror.messageexists.errorInfo: an object with acomponentStackstring. This is the same stack you get asinfo.componentStackincomponentDidCatch. It lists the components that were rendering when the error occurred, innermost first.
Wiring up the callbacks
This example registers both callbacks on the root. Here reportError stands for your own logging function. It is not the browser's built-in window.reportError, so define or import your own under a different name if the clash worries you.
import { createRoot } from "react-dom/client";
const root = createRoot(document.getElementById("root"), {
onCaughtError(error, errorInfo) {
reportError("caught by boundary", error, errorInfo.componentStack);
},
onUncaughtError(error, errorInfo) {
reportError("not caught by any boundary", error, errorInfo.componentStack);
},
});
root.render(<App />);A more complete version sends the report to a logging service and tags it with the kind of error. The function below uses only standard browser APIs, so it runs as shown in a browser.
import { createRoot } from "react-dom/client";
import App from "./App";
function sendToLogger(kind, error, componentStack) {
const payload = {
kind,
message: error instanceof Error ? error.message : String(error),
stack: error instanceof Error ? error.stack : undefined,
componentStack,
url: window.location.href,
time: new Date().toISOString(),
};
// sendBeacon survives page unloads, which matters when the page is crashing.
navigator.sendBeacon("/api/client-errors", JSON.stringify(payload));
}
const root = createRoot(document.getElementById("root"), {
onCaughtError(error, errorInfo) {
sendToLogger("caught", error, errorInfo.componentStack);
},
onUncaughtError(error, errorInfo) {
sendToLogger("uncaught", error, errorInfo.componentStack);
},
});
root.render(<App />);Note the error instanceof Error check. It protects the reporter itself from code that throws a string or null.
How the flow works
The diagram shows which callback fires, depending on whether a boundary exists above the failing component.
Both callbacks run in addition to the other handling. onCaughtError does not replace componentDidCatch. If a boundary defines both, both run.
What counts as caught and uncaught
The names refer to boundaries, not to whether you wrote a try/catch. The rule is simple.
- Caught: React caught the error and gave it to an error boundary.
- Uncaught: React caught the error but no boundary was available to handle it, so the tree was unmounted.
Errors that boundaries never see, such as those thrown in event handlers or in code after an await, also bypass these callbacks in the usual case. React does not route them through the render machinery. There is one important exception: in React 19, an error thrown inside a function passed to startTransition (including async actions) is handled by React and can reach an error boundary, and therefore onCaughtError. Errors in ordinary event handlers still go to the browser, where they appear as a normal uncaught exception and trigger window.onerror.
That leaves a gap. To get a complete picture, pair the root callbacks with browser-level handlers.
window.addEventListener("error", (event) => {
sendToLogger("window.onerror", event.error ?? event.message, "");
});
window.addEventListener("unhandledrejection", (event) => {
sendToLogger("unhandledrejection", event.reason, "");
});Together, the four sources cover rendering errors inside and outside boundaries, plus handler errors and unhandled promise rejections.
Default behavior and what you replace
Before React 19, React re-threw caught errors, and the browser logged them as uncaught exceptions even when a boundary had handled them. Boundary-handled errors therefore looked like crashes in tools that watch window.onerror, which made noise in monitoring.
React 19 changed the defaults.
- A caught error is logged with
console.errorand is no longer re-thrown. - An uncaught error is reported with
window.reportError, which behaves like an uncaught exception and fires theerrorevent onwindow.
When you supply a callback, it replaces the default for that category. If you pass onCaughtError, React no longer calls its default logging for caught errors. That has a practical consequence during development. Your callback should still print something to the console, or errors that boundaries handle will disappear from the console entirely.
const root = createRoot(container, {
onCaughtError(error, errorInfo) {
if (import.meta.env.DEV) {
console.error(error, errorInfo.componentStack);
}
sendToLogger("caught", error, errorInfo.componentStack);
},
});The import.meta.env.DEV flag is provided by Vite. With another bundler, use its equivalent, such as process.env.NODE_ENV !== "production".
Common mistakes
- Reporting twice. If you log in
componentDidCatchand inonCaughtError, each caught error is sent twice. Pick one place. The root callback is usually the better choice because it also covers boundaries you did not write, such as those inside libraries. - Throwing inside a callback. An error inside
onCaughtErrororonUncaughtErrorhas no boundary to catch it. Wrap the body intry/catchor keep the reporter simple and defensive. - Doing slow work synchronously. The callbacks run while React is handling an error. Send data with
sendBeaconor a fire-and-forgetfetch. Do not block on the result. - Forgetting
hydrateRoot. If you server-render, the same options go in the third argument ofhydrateRoot(container, element, options). Missing them there leaves hydrated apps without central reporting. - Assuming the error is an
Error. Always normalize before reading properties.
import { hydrateRoot } from "react-dom/client";
hydrateRoot(document.getElementById("root"), <App />, {
onCaughtError(error, errorInfo) {
sendToLogger("caught", error, errorInfo.componentStack);
},
onUncaughtError(error, errorInfo) {
sendToLogger("uncaught", error, errorInfo.componentStack);
},
onRecoverableError(error, errorInfo) {
sendToLogger("recoverable", error, errorInfo.componentStack);
},
});Choosing between root callbacks and boundary reporting
| Concern | `componentDidCatch` | Root callbacks |
|---|---|---|
| Sees errors from boundaries you did not write | No | Yes |
| Sees errors with no boundary | No | Yes, through `onUncaughtError` |
| Per-boundary context, such as a feature name | Yes, through props | No, but the component stack hints at it |
| Needs React 19 | No | Yes |
A reasonable setup is to use root callbacks for logging and keep boundaries focused on the fallback UI and recovery. When you need per-feature tags, put the feature name in the component names along the stack, or add an onError prop to react-error-boundary for that one case.
Summary of the model
- Every render error in a root ends in one of two places: a boundary (
onCaughtError) or the unmounted tree (onUncaughtError). - Supplying a callback replaces React's default handling for that category.
- Root callbacks do not see event handler or ordinary async errors, so add
windowlisteners for those. - Report in one place to avoid duplicates.
Exercise
Your app has one error boundary around the sidebar. A component outside the sidebar throws during rendering, and the sidebar boundary does not wrap it. Which root callback runs, what happens to the UI, and which callback would run if the sidebar component itself had thrown?
Show answer
onUncaughtError runs, because no boundary is above the failing component. React unmounts the whole tree, so the user sees a blank page unless you add a higher boundary. If the sidebar component had thrown, the sidebar boundary would show its fallback and onCaughtError would run, leaving the rest of the app on screen.
Exercise
After upgrading to React 19, you add an onCaughtError callback that only sends errors to your logging service. In development, errors handled by boundaries no longer appear in the browser console. Why, and how do you fix it?
Show answer
Supplying onCaughtError replaces React's default handler, which was the code that called console.error. Add a console.error call (for example guarded by a development check) inside your callback so the error is still printed.