21 KiB
Error handling
One model for every error, so each variant looks and behaves the same in every project: error boundaries at two sizes, API errors decided by status and by whether the request read data or ran an action, and one empty state. The decisions live in the error handler lib (lib-error-handler.md); this file says where each piece goes and what the user sees. The HTTP lib's HttpError and its codes are in lib-http.md.
Contents: The model · What each failure shows · Boundaries · Reads · Actions · Empty states · B2C/B2B server · Reporting · Copy, accessibility, and i18n · Code · Definition of Done
The model
1) Error boundary ─┬─> Whole app (EB-W)
└─> Section (EB-S): a page or a part
Fallback types ─┬─> Network: the API or the connection failed; retry helps
├─> Logic: a JavaScript bug; retry rarely helps; reported
└─> Outdated: the page runs code from an older deploy; a page reload fixes it
2) API error ─┬─> 5xx ─┬─> Read ───> EB-X
│ └─> Action ─┐
└─> 4xx ─┬─> Action ─┴─> 1. Toast 2. Retry, by cause 3. Guide (the hint)
└─> Read ───> ES (404, 410, 403) | EB-X (the rest)
3) Empty state (ES)
- EB-X is the nearest boundary around the code that failed: the part's EB-S, else the page's EB-S, else EB-W.
- EB-W sits only at the app root, above the root layout, and catches only what nothing below it caught. It replaces the whole app, so it is the last resort.
- EB-S has two sizes. A page-size EB-S sits inside the layouts, so a failed page keeps the header, navigation, and breadcrumbs usable. A part-size EB-S (
PartBoundary) wraps each part that loads on its own, so one failed part never takes down the page (SKILL.md). - Read means getting information: queries, server component reads, and the data a page loads. Action means a write the user started: a mutation or a feature action.
- Reads never toast. A failed read shows where its data would be, as an empty state or a fallback. Actions always toast, because the user is waiting for the result and the page they started from is still there.
- Empty state covers every "nothing to show" case: a successful response with no items, a filter with no matches, a 404 or 410, and a 403.
What each failure shows
classifyError in the lib turns every error into these outcomes (lib-error-handler.md).
| Failure | Read | Action |
|---|---|---|
| 5xx | EB-X, network fallback with Try again; reported | Toast with the support sentence and reference ID; Try again re-runs it when that is safe; reported |
| No response, timeout | EB-X, network fallback with Try again | Toast with the message and hint; Try again when safe |
| 404, 410 | ES not-found |
Toast; Reload loads the latest data |
| 403 | ES no-access |
Toast |
| 400, 422 | EB-X | Field errors, form alert, and toast; the user fixes and resubmits |
| 408 | EB-X, Try again | Toast; the form stays filled and submit is the retry |
| 409 | EB-X | Toast; Reload loads the latest data before the user tries again |
| 429 | EB-X | Toast whose hint says how long to wait; no button |
| 401 | Never reaches the UI: the HTTP lib refreshes, or a failed refresh logs out | Same |
ABORTED |
Nothing | Nothing |
| Logic error (a bug) | EB-X, logic fallback with Reload page and the reference ID; reported | Toast with the support sentence; reported |
| A chunk that failed to load (code from an older deploy) | A page or app boundary reloads the page once; a part boundary shows the outdated fallback with Reload page | Toast that the page was updated, with Reload page; the form keeps its values |
| Success with no items | ES no-data, or no-results when filters or a search are active |
Not an error |
- A failed refetch keeps the data on screen and shows nothing. Only a first load that fails reaches a boundary.
- "When safe" means the action can run twice without harm: an idempotent request (PUT, DELETE, or a POST with an idempotency key the back end honors), or a read-only step. Otherwise the toast has no button, the form keeps its values, and submitting again is the retry.
Boundaries
| Boundary | Where |
|---|---|
| EB-W | apps/<app>/src/app/global-error.tsx |
| EB-S, page | app/<route-group>/error.tsx in every route group, and not-found.tsx at the root and in each group that calls notFound() |
| EB-S, part | PartBoundary, built with Next.js's catchError |
Every boundary renders the same ErrorFallback, which decides what the user sees:
- It classifies the error. A
silentread renders nothing: anABORTEDrequest, or a 401 whose logout redirect is already on its way. not-foundandno-accessrender theStatusEmptyStateat the boundary's size.- Everything else renders island's
ErrorState: the network fallback with Try again, or the logic or outdated fallback with Reload page. They show the reference ID when there is one. - It calls
handleErroronce, in an effect, so the error that stopped here is reported once.
Rules:
- Part boundaries use
catchError, not island'sErrorBoundary:catchErrorletsnotFound()andredirect()through, clears itself on client navigation, and itsretry()renders server parts again on the server. It is a higher-order function, the one exception to "no HOCs in new code" next to React'smemoandlazy(design-patterns.md). global-error.tsxreplaces the root layout, so it has no providers and no styles: it renders its own<html>and<body>, importsapp.cssand the client i18n setup itself, and offers Reload page.- Retry resets the failed queries first, then the boundary. Otherwise a query that threw keeps its error and throws again at once. There is no provider for this:
useQueryErrorResetBoundary()returns the global reset. - In a part boundary, an error with a
digestcame from the server, so Try again callsretry(). A browser-side error callsreset(), which re-renders without a server round trip. - Put
PartBoundaryoutside the part's<Suspense>, so the fallback replaces the skeleton and the part together. Widgets that load inside a form, such as select options and lazy tabs, get their ownPartBoundary, so their failure never unmounts the form and loses what the user typed. LoadOnVisibleand dynamic imports need nothing extra: a chunk that fails to load throws to the part's boundary (rendering-patterns.md), and the error handler classifies it as outdated.- An outdated error at page or app size reloads the page at once, because the page is already gone: at most once a minute, with the time kept in local storage, and only while the browser is online. Otherwise the boundary shows the outdated fallback. A part boundary never reloads on its own, because the user may be typing elsewhere on the page; it offers Reload page. The deploy rules that keep these errors rare are in b2c-b2b.md.
Reads
configs/react-query.tssetsthrowOnError: (_error, query) => query.state.data === undefined. A first load that fails throws to its boundary; a refetch that fails keeps the data and shows nothing. Parts guard onlyisPending, neverisError, so no component has an error branch.useSuspenseQueryalways throws on a failed first load, whateverthrowOnErrorsays, so it reaches the same boundary.QueryCache.onErrorcallshandleError(error, { where: 'refetch' })only when the query still has data: that is the one place a failed refetch stops. A first load is handled by its fallback instead.- Queries don't retry on their own (
retry: false), because the HTTP lib already retried idempotent requests. The user retries from the fallback. networkMode: 'offlineFirst'for queries and mutations, so an offline request fails at once and shows the network fallback or toast, instead of pausing with a skeleton or spinner that never ends.- A read whose 404 or 403 is an expected answer (a detail page, an order that may belong to someone else) needs no special code: the fallback turns it into the
not-foundorno-accessempty state.
Actions
- A form catches the action's error in
form.handleSubmitand callsapplyServerErrors. Anything else callsshowActionErrorin itscatchor inuseMutation'sonError. Code: code-patterns.md. showActionErroris the one error toast: it callshandleError, returns early forsilenterrors, and showstoast.errorwith:- the title: what failed, from the caller's
failedMessage, naming the object ("Category 'Kitchenware' wasn't saved"); - the description: the error's message and hint (the guide), or, when there is neither (5xx, unknown, logic), one support sentence with the reference ID;
- a button from the retry kind: Try again for
againwhen the caller passesretry, Reload forreloadwhen the caller passesreload, Reload page forreload-page, and none forwait,fix, andnone; duration: Infinity, anidbuilt fromfailedMessageso a repeated failure replaces its toast instead of stacking, andtestId: 'action-error'.
- the title: what failed, from the caller's
applyServerErrorsputs each server field error under its field and focuses the first, puts field errors for fields the form doesn't render (and whole-submission errors) in the form alert, and then callsshowActionError. The form keeps every value.- The caller passes
retryonly when running the action again is safe (see What each failure shows). Passreloadfor actions on data that can change underneath the user (409, 404): it invalidates or refetches the affected queries, and the user tries again on fresh data. - An action that runs inside
startTransitioncatches its error inside the transition. An error thrown out of a transition goes to the nearest error boundary and replaces the part, which is wrong for an action. - Uploads and multi-step flows keep a
failedstate in their reducer and also callshowActionError, with aretrythat starts the flow again with the same file (design-patterns.md). - Login and OTP requests send
skipRefresh: true, and the back-end contract answers wrong credentials with 400 or 422 and field errors. So a 401 always means "no valid session", and the login form never triggers a refresh.
Empty states
- island has one
EmptyStatemolecule (packages/island/src/molecules/empty-state/) with the variantsno-data,no-results,not-found, andno-access, and the sizespartandpage. Each variant has its own illustration. It takes the title, description, and an optional action as props, so each use gives its own copy. - Its sibling
ErrorStatemolecule has the same sizes and slots, plus areferenceIdline, for the fallbacks. no-dataandno-resultscome from successful responses: the template renders them from the model's data, with feature copy and a primary action ("No categories yet. Create your first category to start organizing products." and "Create category").no-resultsoffers "Clear filters".not-foundandno-accesscome from errors. The app'sStatusEmptyStaterenders them with shared copy from theerrorsnamespace; the page size adds a link to the home page.- A list part that hides itself when empty, such as a related-products rail, may render nothing instead. Decide it in the plan, not per render.
B2C/B2B server
Server reads classify on the server, because a Server Component error reaches the browser with only its digest.
- The page reads its main data through
readOnServer, a server-only helper in the platform'sapp/error-boundaries/. It returns{ status: 'ok', data }, ornot-foundfor 404 and 410 andno-accessfor 403, and rethrows the rest to the page'serror.tsx. Server reads send no auth cookies, so only pages that are the same for every visitor read on the server; a page that needs a logged-in user loads in the browser (rendering-patterns.md). - Where
notFound()runs decides the status:- An indexable page has nothing above it that streams: no
loading.tsx, and no<Suspense>aroundchildrenin a layout or in a component that a layout renders around them (b2c-b2b.md). On an entity page (product, category, brand, seller, article, store branch, campaign),generateMetadataand the page call one read helper. The helper reads throughreadOnServerand the page's cache, callsnotFound()fornot-found, and callspermanentRedirect()when the payload names a replacement (error-handling-code.md).generateMetadataruns before the first byte, so crawlers get a real 404 withnoindexin<head>, at no extra read, or a 308 withLocation. The page's call covers a request without aUser-Agent, whose metadata streams. - The server HTML of a real 404 has an empty
<body>, and the group'snot-found.tsxrenders in the browser. Google needs only the status, and it may not render a non-200 page at all. - Moves known in advance, such as a renamed category tree, go in
redirects()innext.config.ts, which answers before any render. A redirect thrown while the shell renders, or a failed read thatgenerateMetadatarethrows, makes Next.js render again with a fresh cache, so the read runs twice. A back-end outage therefore doubles the reads thatgenerateMetadataawaits, as on entity pages. - A
noindexor blocked page keeps itsloading.tsx, so its status is already 200 whennotFound()runs. Next.js then adds anoindexrobots tag, in<head>whengenerateMetadatathrows and at the end of<body>when the page throws, and renders the not-found UI only in the browser. A redirect becomes a<meta http-equiv="refresh">.
- An indexable page has nothing above it that streams: no
no-accessrenders the page-sizeStatusEmptyState, andgenerateMetadatareturnsrobots: { index: false }for it. Likenot-foundand every error page, it renders no JSON-LD (lib-json-ld.md).forbidden()andunauthorized()are experimental and not used (rendering-patterns.md).- A server part reads through
readOnServertoo: it renders the part-sizeStatusEmptyStatefornot-foundandno-access, and rethrows the rest to itsPartBoundary. - A part that must show an empty state awaits its read on the server. An un-awaited prefetch streams its error to the browser as a digest, so use it only for reads that can't answer 404 or 403.
shouldRedactErrors: () => falsein the dehydrate options keeps the real error on the server, so Next.js reports it and the browser gets its digest instead of a generic "redacted" error. error.tsxandglobal-error.tsxrender<meta name="robots" content="noindex" />, so an error page is never indexed.instrumentation.tsconfigures the error handler for the server and callshandleErrorfromonRequestError(lib-error-handler.md).
Status per case, measured on Next.js 16.4. No page answers 410: Google treats it like 404, and Next.js has no API for it.
| Case | Status | The server HTML holds |
|---|---|---|
| Entity missing | 404 | noindex in <head> and an empty <body>; not-found.tsx renders in the browser |
| Entity replaced by another | 308 to the replacement | nothing that matters |
| Product out of stock, or discontinued with its content kept | 200, indexable | the page, with its stock text, and its availability in the JSON-LD |
| Listing page past the last; empty, duplicate, or unknown combination of indexable filters | 404 | as for a missing entity |
Empty listing whose URL includes a filter that robots.ts blocks |
200 | the listing, with the no-results empty state and Clear filters |
| Category with no products | 200 with noindex while the menu links it; 404 once it leaves the menu |
the page, with the no-data empty state |
| Search with no results | 200; /search is blocked in robots.ts |
the no-results empty state; never 5xx for an unknown query |
A failed read on an indexable page, in generateMetadata, the page entry, or another Server Component outside every <Suspense> |
500 | noindex and an empty <body>; error.tsx renders in the browser |
A failed read in a part inside its <Suspense> and PartBoundary |
200 | the part's skeleton; the PartBoundary fallback renders in the browser |
A failed read in a layout above the page, such as the (shop) layout's getMenu() |
500, on every page under that layout | noindex and an empty <body> |
notFound() on a noindex or blocked page, under its loading.tsx |
200 | the skeleton and noindex; the not-found UI renders in the browser |
A failed read on a noindex or blocked page, under its loading.tsx |
200 | the skeleton; a noindex page keeps the noindex of its metadata export, and a blocked page has no robots tag; error.tsx and its noindex render in the browser |
| Overload | 503 with Retry-After, from the reverse proxy or the CDN |
— |
Reporting
handleErrorruns once per error, where it stops: a fallback,showActionError,QueryCache.onError, or the server'sonRequestError. Never call it in a repository, an action, or acatchthat rethrows.- It reports 5xx and logic errors only, with the request id and digest. 4xx, network, and timeout errors aren't bugs; the HTTP lib's breadcrumbs keep them visible next to a reported error.
- The bootstrap passes the Sentry integration's adapter as
report. The adapter maps anErrorReportto the vendor's event (tags:where,status,code; context:requestId,digest,name) and filters noise that isn't the app's bug, such as errors thrown by browser extensions. - No failure events on the event emitter: events announce completed operations only (design-patterns.md).
Copy, accessibility, and i18n
- Every fallback, empty state, and toast says what happened and what the user can do, following the copy rules in ui-rules.md. Unknown errors say: "Something went wrong on our side. Try again in a moment. If it keeps happening, contact support and mention reference ID
a1b2c3." - The
errorsnamespace loads on every route, because any route can fail. It holds the HTTP lib's keys (http.network,http.timeout, their hints, andhttp.retry-after), the support sentences, the fallback copy (network,logic, andoutdated), theapp.outdatedmessage, thenot-foundandno-accesscopy, and the button labels. - Server field errors and messages arrive translated; never pass them through
tagain. - Page and app fallbacks move focus to their heading (
tabIndex={-1}), so keyboard and screen-reader users land on the explanation. Part fallbacks don't take focus and have no live role, so a failed part never interrupts what the user is doing elsewhere. - One
<Toaster>in the AppShell, withdirfrom the locale and its position on the logical end side (bottom-rightin LTR,bottom-leftin RTL).
Code
The boundaries, ErrorFallback, readOnServer, and the query client's error settings are in error-handling-code.md. Read it only when you build or change one of them.
Definition of Done
[ ] The app has EB-W; every page and every part that loads on its own has an EB-S, and every boundary renders ErrorFallback
[ ] Reads never toast: 404 and 410 show the not-found empty state, 403 no-access, and other failures their boundary's fallback
[ ] A failed refetch keeps its data; no component has an isError branch
[ ] Every failed action shows the action-error toast with its hint or the support sentence and reference ID; the form keeps its values
[ ] Server field errors sit under their rendered fields and the rest in the form alert
[ ] Retry follows the retry kind: again only when safe, reload for 409 and 404, a wait hint for 429, fix and resubmit for other 4xx
[ ] A chunk that failed to load reloads the page once at page or app size, offers Reload page in parts and toasts, and isn't reported
[ ] ABORTED and 401 never show anything
[ ] Successful empty responses show the no-data or no-results empty state with a next step
[ ] handleError runs once per error, where it stops; 5xx and logic errors reach the tracker with requestId or digest
[ ] Server reads go through readOnServer; error pages and no-access pages are noindex
[ ] Indexable pages have no loading.tsx, and no Suspense around children, above them; an entity page's generateMetadata answers a missing entity with notFound() (404) and a replaced one with permanentRedirect() (308) before the first byte