Sub topic 10
Reporting errors with component stacks
This chapter assumes you can write a class-based error boundary with getDerivedStateFromError and componentDidCatch. It also assumes you know which errors boundaries do not catch, and that you have used fetch and async/await. Here you will send the errors a boundary catches to a logging service, with enough context to find the cause.
Why the fallback is not enough
A fallback UI tells the user something broke. It tells you nothing. If a boundary swallows an error and shows "Something went wrong", the error exists only in that user's browser. You will not know about it unless the user complains.
Reporting closes that gap. A useful report answers three questions:
- What was thrown? The
errorobject gives you the message, the name, and the JavaScript stack trace. - Where in the component tree did it happen? The component stack answers this.
- Under what conditions? That means the URL, the app version, and the user's session.
Two kinds of stack
An error carries two different stacks, and they answer different questions.
| Stack | Where it comes from | What it shows |
|---|---|---|
| JavaScript stack (`error.stack`) | The JavaScript engine | The chain of function calls, with file names and line numbers |
| Component stack (`info.componentStack`) | React | The chain of components, from the one that threw up to the root |
The JavaScript stack usually points at the function that threw. The component stack shows which part of the UI was rendering. A component such as Avatar may be rendered in twenty places, and the component stack shows which parent chain led to the failing instance.
A component stack is a plain string. Each line starts with at and names a component, as in this example:
at Avatar (http://localhost:5173/src/Avatar.jsx:4:18)
at div
at Profile (http://localhost:5173/src/Profile.jsx:9:3)
at ErrorBoundary (http://localhost:5173/src/ErrorBoundary.jsx:3:1)
at App (http://localhost:5173/src/App.jsx:6:3)Read it from the top. Avatar threw. It was rendered inside a div, inside Profile, inside the boundary.
Where React hands you the stack
React passes the component stack to componentDidCatch as the second argument. The argument is an object, and its componentStack property holds the string.
The two boundary methods run at different times, and that affects where reporting code can go:
getDerivedStateFromErrorruns during the render phase. React may call render-phase code more than once, so it must be pure. Do not send network requests from it.componentDidCatchruns during the commit phase, after the fallback has been rendered. Side effects are allowed here. This is where reporting belongs.
A reporting helper
Keep the transport code out of the boundary, so you can reuse it for the root callbacks later in this chapter. This helper builds a report and sends it.
// sendErrorReport.js
const ENDPOINT = "/api/client-errors"; // replace with your service
export function sendErrorReport({ error, componentStack, source }) {
const report = {
source, // "boundary", "root-caught", "root-uncaught", ...
name: error?.name ?? "UnknownError",
message: String(error?.message ?? error),
stack: error?.stack ?? null,
componentStack: componentStack ?? null,
url: window.location.href,
userAgent: navigator.userAgent,
timestamp: new Date().toISOString(),
};
const body = JSON.stringify(report);
// sendBeacon survives page unloads. Fall back to fetch if it refuses.
const queued =
typeof navigator.sendBeacon === "function" &&
navigator.sendBeacon(ENDPOINT, new Blob([body], { type: "application/json" }));
if (!queued) {
fetch(ENDPOINT, {
method: "POST",
headers: { "Content-Type": "application/json" },
body,
keepalive: true,
}).catch(() => {
// Reporting must never throw. Swallow transport failures.
});
}
}The helper has two safety rules. It must never throw, because an error inside componentDidCatch is itself an error, and it would escape to the next boundary up. It must also not block rendering, so it sends the report and returns.
Wiring the helper into a boundary
The boundary below accepts an optional onError prop. The boundary stays generic, and the app decides where errors go.
import { Component } from "react";
import { sendErrorReport } from "./sendErrorReport";
export class ErrorBoundary extends Component {
state = { error: null };
static getDerivedStateFromError(error) {
return { error };
}
componentDidCatch(error, info) {
sendErrorReport({
error,
componentStack: info.componentStack,
source: "boundary",
});
this.props.onError?.(error, info);
}
render() {
if (this.state.error) {
return this.props.fallback;
}
return this.props.children;
}
}Do not call setState in componentDidCatch to switch to the fallback. That is an older pattern. getDerivedStateFromError is the supported way to render the fallback, and componentDidCatch is for side effects only.
Reporting with react-error-boundary
The react-error-boundary library has an onError prop. Its callback receives the error and an info object with componentStack, so you can reuse the same helper.
import { ErrorBoundary } from "react-error-boundary";
import { sendErrorReport } from "./sendErrorReport";
function Fallback({ resetErrorBoundary }) {
return (
<div role="alert">
<p>Something went wrong.</p>
<button onClick={resetErrorBoundary}>Try again</button>
</div>
);
}
function logToService(error, info) {
sendErrorReport({
error,
componentStack: info.componentStack,
source: "boundary",
});
}
export function Page({ children }) {
return (
<ErrorBoundary FallbackComponent={Fallback} onError={logToService}>
{children}
</ErrorBoundary>
);
}If you route event handler errors to a boundary with showBoundary, they also arrive in onError. Those errors were not thrown during rendering, but React still attaches a component stack, because the boundary treats them as render errors on its next render.
Reporting at the root in React 19
Per-boundary reporting has a gap. Errors that no boundary catches never reach componentDidCatch. React 19 adds two callbacks on createRoot that cover every case in one place.
import { createRoot } from "react-dom/client";
import { sendErrorReport } from "./sendErrorReport";
import App from "./App";
const root = createRoot(document.getElementById("root"), {
onCaughtError(error, errorInfo) {
sendErrorReport({
error,
componentStack: errorInfo.componentStack,
source: "root-caught",
});
},
onUncaughtError(error, errorInfo) {
sendErrorReport({
error,
componentStack: errorInfo.componentStack,
source: "root-uncaught",
});
},
});
root.render(<App />);onCaughtErrorfires when a boundary caught the error.onUncaughtErrorfires when no boundary caught it. The tree unmounts in this case.
If you report from the root, do not also report from every boundary. Otherwise each caught error arrives twice. Pick one of these designs:
- Report only at the root. Boundaries stay simple and only render fallbacks. This needs React 19.
- Report in each boundary through
onError. This works on React 18 and earlier, but errors that no boundary catches need a separate path.
Setting either root callback replaces React's default console logging for that case. If you still want console output during development, call console.error yourself inside the callback.
What makes a component stack useful
Minified names
In a production build, the minifier renames functions. Your component Avatar may appear as a or t in the stack. A report full of at t and at e tells you very little.
There are two usual fixes:
- Upload source maps to your logging service. Most services use them to restore names in the JavaScript stack. Check whether your service also rewrites component stack lines, because support varies.
- Configure your minifier to keep component names. This makes bundles slightly larger, so it is a trade-off.
Anonymous components
Components created inline, or wrapped by higher-order functions, can show up as Anonymous or with a generic name. Give components named function declarations, and set displayName on wrapped components, so the stack stays readable.
Add your own context
The component stack shows structure, not data. It does not say which user or document triggered the failure. Add context in the onError handler. For example, include the route, the app version, and an anonymous session ID.
Keeping reports clean and safe
- Strip private data. Error messages can contain user input, such as
Invalid email: [email protected]. Scrub or truncate messages before sending them, and never send tokens or form contents. - Deduplicate. A component that fails on every render attempt can send many identical reports, especially after repeated retries. Keep a small in-memory set keyed on message plus the first lines of the component stack, and skip repeats.
- Rate-limit. Cap the reports per page session, for example to 20. A broken page should not flood your own endpoint.
- Don't report in development. Local errors are noise. Check
import.meta.env.PROD(Vite) or your bundler's equivalent before sending. - Remember recovered errors. If the user clicks "Try again" and the error returns, that is a second report. Include a retry count if you want to tell the cases apart.
Common mistakes
- Sending the report from
getDerivedStateFromError. It runs in the render phase and can run more than once, so it can send duplicates. - Letting the reporter throw. A failing
fetchinsidecomponentDidCatchbecomes a new error. Always catch transport failures. - Reporting only
error.message. Without the stack and component stack you cannot locate the failure. - Reporting from both the root callbacks and the boundaries, which doubles every caught error.
- Assuming errors in event handlers or after an
awaitreachcomponentDidCatch. They do not, unless you route them withshowBoundaryor a similar technique.
Check your understanding
Exercise
A boundary reports errors from both componentDidCatch and the onCaughtError callback on createRoot. Your dashboard shows two reports for every error that a boundary catches. What is the cause, and how do you fix it?
Show answer
Each caught error triggers both reporting paths, so it is sent twice. Pick one path. Either report only at the root, with onCaughtError for caught errors and onUncaughtError for the rest, or report only in the boundaries and handle uncaught errors separately. Remove the other call.
Exercise
Why must the network request live in componentDidCatch rather than getDerivedStateFromError?
Show answer
getDerivedStateFromError runs in the render phase, which must be free of side effects and may run more than once. componentDidCatch runs in the commit phase, after the fallback is rendered, so side effects such as sending a report are allowed there.
Exercise
A production report contains the component stack lines at t, at e, and at n. What can you do to make it readable?
Show answer
The minifier has renamed the components. Upload source maps to your logging service if it can apply them to component stacks. You can also configure the minifier to keep function names. Naming components with function declarations or displayName keeps the original names useful.