wealth/.claude/skills/front-end-architect/references/error-handling.md

17 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 shell, 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 shell, 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:

  1. It classifies the error. A silent read renders nothing: an ABORTED request, or a 401 whose logout redirect is already on its way.
  2. not-found and no-access render the StatusEmptyState at the boundary's size.
  3. 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.
  4. It calls handleError once, in an effect, so the error that stopped here is reported once.

Rules:

  • Part boundaries use catchError, not island's ErrorBoundary: catchError lets notFound() and redirect() through, clears itself on client navigation, and its retry() 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's memo and lazy (design-patterns.md).
  • global-error.tsx replaces the root layout, so it has no providers and no styles: it renders its own <html> and <body>, imports app.css and 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 digest came from the server, so Try again calls retry(). A browser-side error calls reset(), which re-renders without a server round trip.
  • Put PartBoundary outside 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 own PartBoundary, so their failure never unmounts the form and loses what the user typed.
  • LoadOnVisible and 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.ts sets throwOnError: (_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 only isPending, never isError, so no component has an error branch.
  • useSuspenseQuery always throws on a failed first load, whatever throwOnError says, so it reaches the same boundary.
  • QueryCache.onError calls handleError(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-found or no-access empty state.

Actions

  • A form catches the action's error in form.handleSubmit and calls applyServerErrors. Anything else calls showActionError in its catch or in useMutation's onError. Code: code-patterns.md.
  • showActionError is the one error toast: it calls handleError, returns early for silent errors, and shows toast.error with:
    • 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 again when the caller passes retry, Reload for reload when the caller passes reload, Reload page for reload-page, and none for wait, fix, and none;
    • duration: Infinity, an id built from failedMessage so a repeated failure replaces its toast instead of stacking, and testId: 'action-error'.
  • applyServerErrors puts 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 calls showActionError. The form keeps every value.
  • The caller passes retry only when running the action again is safe (see What each failure shows). Pass reload for 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 startTransition catches 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 failed state in their reducer and also call showActionError, with a retry that 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 EmptyState molecule (packages/island/src/molecules/empty-state/) with the variants no-data, no-results, not-found, and no-access, and the sizes part and page. 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 ErrorState molecule has the same sizes and slots, plus a referenceId line, for the fallbacks.
  • no-data and no-results come 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-results offers "Clear filters".
  • not-found and no-access come from errors. The app's StatusEmptyState renders them with shared copy from the errors namespace; 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's app/error-boundaries/. It returns { status: 'ok', data }, or not-found for 404 and 410 and no-access for 403, and rethrows the rest to the page's error.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).
  • not-found calls notFound(), which renders the group's not-found.tsx. When the page has already started streaming (it has a loading.tsx), the status stays 200 and Next.js adds a noindex robots tag, which search engines treat as not found.
  • no-access renders the page-size StatusEmptyState, and generateMetadata returns robots: { index: false } for it. Like not-found and every error page, it renders no JSON-LD (lib-json-ld.md). forbidden() and unauthorized() are experimental and not used (rendering-patterns.md).
  • A server part reads through readOnServer too: it renders the part-size StatusEmptyState for not-found and no-access, and rethrows the rest to its PartBoundary.
  • 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: () => false in 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.tsx and global-error.tsx render <meta name="robots" content="noindex" />, so an error page is never indexed.
  • instrumentation.ts configures the error handler for the server and calls handleError from onRequestError (lib-error-handler.md).

Reporting

  • handleError runs once per error, where it stops: a fallback, showActionError, QueryCache.onError, or the server's onRequestError. Never call it in a repository, an action, or a catch that 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 an ErrorReport to 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 b2c-b2b.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 errors namespace loads on every route, because any route can fail. It holds the HTTP lib's keys (http.network, http.timeout, their hints, and http.retry-after), the support sentences, the fallback copy (network, logic, and outdated), the app.outdated message, the not-found and no-access copy, and the button labels.
  • Server field errors and messages arrive translated; never pass them through t again.
  • 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, with dir from the locale and its position on the logical end side (bottom-right in LTR, bottom-left in 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