Handling Errors
Part of the Next.js Essentials section of Coddy's React journey — lesson 27 of 47.
Loads fail. The database is down, the record is gone, something throws. Without a plan, one bad await takes the whole screen with it.
error.jsx is the mirror image of loading.jsx: same idea, opposite outcome. Drop it beside a page and it catches anything that page throws while rendering:
app/
menu/
page.jsx
loading.jsx while it works
error.jsx when it doesn'tUnlike loading.jsx, it has one hard requirement:
'use client';
export default function Error({ error, reset }) {
return (
<div>
<h2>Couldn't load the menu</h2>
<button onClick={reset}>Try again</button>
</div>
);
}error.jsx must be a client component. The reason is right there in the JSX: onClick. A retry button is interactivity, and interactivity needs a component that ships to the browser. Leave off 'use client' and you get the event-handler error from the last chapter, on the very page whose job was to handle errors.
It receives two props:
error: the Error that was thrown, so you can log itreset: a function that re-renders the failed section. Call it and the page tries again
reset is what makes this more than a nicer crash screen. A blip that failed once will often work the second time, and the user never had to reload anything.
Like the other special files, error.jsx covers its own folder and everything nested below it, so one file near the root is a safety net for a whole section of the site.
Try it yourself
This lesson doesn't include a code challenge.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Next.js Essentials
2Routing & Links
Folders Are RoutesNested RoutesLinking PagesDynamic RoutesNot Found PagesRecap: Routing5Data on the Server
Async ComponentsAwaiting Route ParamsTwo Fetches at OnceLoading StatesHandling ErrorsRecap: Data Fetching