Sub topic 2
What Error Boundaries Do Not Catch
Assume you know React function components, JSX, props, state, and try/catch. This chapter focuses on errors that happen outside normal rendering and on choosing a useful boundary location.
Errors a Boundary Does Not Catch
An error boundary catches errors thrown while React renders a descendant, runs a descendant lifecycle method, or evaluates a descendant constructor. It does not catch every JavaScript error in the application.
A boundary does not catch:
- Errors in event handlers, such as a button's
onClick. - Errors in asynchronous callbacks, timers, and Promise chains.
- Errors during server-side rendering.
- Errors thrown by the boundary itself.
- Errors in code outside the React tree.
Handle event and asynchronous errors at their source. An uncaught rendering error can unmount the entire React tree, so use a boundary to limit that damage.
Getting Event and Async Errors into a Boundary
Use local try/catch when the failure belongs to one control. If the application should show the same boundary fallback, react-error-boundary provides showBoundary.
import { ErrorBoundary, useErrorBoundary } from "react-error-boundary";
function Fallback({ error, resetErrorBoundary }) {
return (
<div role="alert">
<p>Could not save: {error.message}</p>
<button onClick={resetErrorBoundary}>Try again</button>
</div>
);
}
function SaveButton({ save }) {
const { showBoundary } = useErrorBoundary();
async function handleClick() {
try {
await save();
} catch (error) {
showBoundary(error);
}
}
return <button onClick={handleClick}>Save</button>;
}
function Editor({ documentId, save }) {
return (
<ErrorBoundary
FallbackComponent={Fallback}
resetKeys={[documentId]}
>
<SaveButton save={save} />
</ErrorBoundary>
);
}Where to Place Boundaries
Place a boundary around a unit that can fail independently, such as a dashboard panel, editor, or route. A page-level boundary protects navigation but replaces more content. Several smaller boundaries preserve more of the interface but can create more fallback messages.
| Placement | Benefit | Cost |
|---|---|---|
| Around the whole app | Last-resort protection | A failure hides most of the app |
| Around a route | Clear page fallback | The whole route disappears |
| Around one widget | Other widgets continue working | More boundaries to design and test |
Exercise
Will an error thrown inside setTimeout be caught by an error boundary?
Show answer
No. Catch it in the asynchronous code, or call showBoundary when the library-level fallback is appropriate.