Sub topic 10
Reporting errors with component stacks
This chapter assumes you can write a class-based error boundary, you know what it catches, and you are comfortable with fetch and async/await. Here you will send caught errors to a logging service together with the information needed to find the failing component.
Why the JavaScript stack is not enough
An error's stack property shows which functions were running when it was thrown. In a React app, those frames are mostly React internals and your bundled code. They do not show which components were mounted around the failure.
React gives you a second piece of data for that: the component stack. It lists the components that were rendering when the error occurred, from the failing one up to the root. A stack such as at Avatar, at ProfileHeader, at Profile tells you where in the tree to look.
Where the component stack comes from
React passes the component stack to componentDidCatch as the second argument. It is the componentStack string on the info object.
The two lifecycle methods have separate jobs:
| Method | Phase | Use it for |
|---|---|---|
| `getDerivedStateFromError` | Render | Returning state that switches to the fallback |
| `componentDidCatch` | Commit | Side effects such as logging |
Never log from getDerivedStateFromError. React can call render-phase code more than once, and it should have no side effects.
A reporting function
Write the reporting code as a small function that you can reuse from any boundary. It is named logError to avoid clashing with the browser's global reportError.
export function logError(error, componentStack) {
const payload = {
message: error.message,
name: error.name,
stack: error.stack,
componentStack,
url: window.location.href,
time: new Date().toISOString(),
};
try {
fetch("/api/client-errors", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
keepalive: true,
}).catch(() => {});
} catch {
// Reporting must never throw. A failure here would hide the original error.
}
}The keepalive option lets the request finish even if the user navigates away. The empty catch handlers are deliberate. If the logger itself threw inside a lifecycle method, the exception would escape the boundary and could unmount the tree.
Calling it from the boundary
import { Component } from "react";
import { logError } from "./logError";
class ErrorBoundary extends Component {
state = { error: null };
static getDerivedStateFromError(error) {
return { error };
}
componentDidCatch(error, info) {
logError(error, info.componentStack);
}
render() {
if (this.state.error) {
return this.props.fallback;
}
return this.props.children;
}
}The same idea with react-error-boundary
The library's onError prop receives the same two arguments, so function-component codebases can reuse logError unchanged.
import { ErrorBoundary } from "react-error-boundary";
import { logError } from "./logError";
function App() {
return (
<ErrorBoundary
fallback={<p>Something went wrong.</p>}
onError={(error, info) => logError(error, info.componentStack)}
>
<Profile />
</ErrorBoundary>
);
}Common problems
- Minified names. In a production build, component names are shortened, so a stack reads
at t,at e. Upload source maps to your logging service, or use a service that does this for you, so stacks are translated back. - Duplicate reports. One bug can fire on every re-render or retry. Deduplicate on the message and the first line of the component stack, or rate-limit on the server.
- Sensitive data. Error messages and URLs can contain user IDs, tokens, or query strings. Strip or redact them before sending.
- Boundary not reached. Errors from event handlers and async code do not reach
componentDidCatch. Send them to a boundary withshowBoundary, or calllogErrordirectly. In that case there is no component stack, so passundefinedor record the action that failed.
Exercise
A teammate puts logError(error, info.componentStack) inside getDerivedStateFromError, but info is undefined and reports are duplicated. What is wrong, and how do you fix it?
Show answer
getDerivedStateFromError receives only the error, not info. It runs during render, so it must be free of side effects, and React may call it more than once, which explains the duplicates. Return { error } from it and move the logError(error, info.componentStack) call into componentDidCatch, which runs after commit and receives the component stack.