Sub topic 6
Getting event handler and async errors into a boundary
This chapter assumes you can write React function components with hooks, you know throw and try/catch, and you are comfortable with Promises and async/await. It also assumes you have seen a class-based error boundary, as in the earlier chapters.
Why boundaries miss these errors
An error boundary catches errors that React itself sees: errors thrown while rendering, in lifecycle methods, and in constructors of components below it. Event handlers are different. React does not call them during rendering, so a throw inside one does not interrupt a render. The same is true for code that runs after an await, inside a setTimeout callback, or in a Promise .then. By the time that code throws, React is no longer running your component.
The result is that the error appears in the console, but no fallback UI is shown and the component stays on screen.
function BrokenButton() {
function handleClick() {
throw new Error("Not caught by any boundary");
}
return <button onClick={handleClick}>Click me</button>;
}Wrapping BrokenButton in a boundary changes nothing. The click handler throws, the browser logs the error, and the page keeps working with the old UI.
The default fix: handle it where it happens
Often the right answer is not a boundary at all. A failed save is usually a local problem, so show a local message and let the user retry.
import { useState } from "react";
function SaveButton() {
const [message, setMessage] = useState(null);
async function handleClick() {
try {
await save();
setMessage(null);
} catch (error) {
console.error(error);
setMessage("Could not save. Please try again.");
}
}
return (
<div>
<button onClick={handleClick}>Save</button>
{message && <p role="alert">{message}</p>}
</div>
);
}Use this approach when the rest of the component is still usable after the failure.
Sending the error to a boundary
Sometimes the failure leaves the component in a state where it cannot continue, and you want the same fallback UI you use for render errors. The pattern is to catch the error and then rethrow it during a render.
React rethrows errors thrown during rendering to the nearest boundary. A state update can trigger a render, so you store the error in state and throw it from the component body.
import { useState } from "react";
function useThrowToBoundary() {
const [error, setError] = useState(null);
if (error) {
throw error;
}
return setError;
}
function SaveButton() {
const throwToBoundary = useThrowToBoundary();
async function handleClick() {
try {
await save();
} catch (error) {
throwToBoundary(error);
}
}
return <button onClick={handleClick}>Save</button>;
}After setError(error) runs, React re-renders SaveButton. The throw now happens during rendering, so the nearest boundary catches it and shows its fallback.
The same pattern with react-error-boundary
The react-error-boundary library packages this pattern as the useErrorBoundary hook. Its showBoundary function does what useThrowToBoundary does above.
import { useErrorBoundary } from "react-error-boundary";
function SaveButton() {
const { showBoundary } = useErrorBoundary();
async function handleClick() {
try {
await save();
} catch (error) {
showBoundary(error);
}
}
return <button onClick={handleClick}>Save</button>;
}The component must be rendered inside an ErrorBoundary from the same library. The hook relies on that boundary being present.
Common errors
- Forgetting the
try/catch. Anasynchandler returns a Promise. If it rejects and nothing handles it, you get an unhandled rejection, not a boundary fallback. - Calling
showBoundaryorsetErrorwith a non-error value. Pass the caught error object so the fallback and your logging have a message and a stack. - Routing every failure to a boundary. A fallback replaces the whole subtree. For a failed form submission, an inline message is usually a better experience.
- Missing boundary. If no boundary is above the component, the rethrown error is uncaught and React unmounts the whole tree.
Exercise
A component calls fetch inside a useEffect, and the request fails. The component is wrapped in an error boundary, but the fallback never appears. Why, and what is the smallest change that would show the fallback?
Show answer
The failure happens in asynchronous code, after React has finished rendering, so the boundary never sees it. Catch the error in the effect, for example with .catch(showBoundary) using useErrorBoundary, or store it in state and throw it during render. The thrown error then happens during a render, and the nearest boundary shows its fallback.