# Error handling code The code for [error-handling.md](error-handling.md): island's error boundary, `ErrorFallback`, the part, page, and app boundaries, `readOnServer`, and the query client's error settings. Read it only when you build or change one of these. A feature that uses them needs only error-handling.md. Paths are relative to `platforms//src/`, as in [code-patterns.md](code-patterns.md). Each `error-boundaries//` module is shaped like `guards/`: the component or function, its `types.ts`, and `index.ts`. **island's error boundary.** `packages/island/src/primitives/error-boundary/ErrorBoundary.tsx` is a class, because React has no hook for catching render errors. It knows nothing about HTTP or reporting; the fallback does that. Its `types.ts` declares `ErrorBoundaryProps`: `children`, `fallback: (props: { error: unknown; reset: () => void }) => ReactNode`, `onReset?`, and `resetKeys?: readonly unknown[]`. ```tsx 'use client'; import { Component } from 'react'; import type { ErrorBoundaryProps } from './types'; type ErrorBoundaryState = { hasError: boolean; error: unknown }; export class ErrorBoundary extends Component { state: ErrorBoundaryState = { hasError: false, error: null }; static getDerivedStateFromError(error: unknown): ErrorBoundaryState { return { hasError: true, error }; } componentDidUpdate(previous: ErrorBoundaryProps) { const keys = this.props.resetKeys ?? []; const changed = keys.some((key, index) => !Object.is(key, previous.resetKeys?.[index])); if (this.state.hasError && changed) this.reset(); } reset = () => { this.props.onReset?.(); this.setState({ hasError: false, error: null }); }; render() { if (!this.state.hasError) return this.props.children; return this.props.fallback({ error: this.state.error, reset: this.reset }); } } ``` **The fallback.** `app/error-boundaries/error-fallback/ErrorFallback.tsx`. `size` is `'app' | 'page' | 'part'`; island's molecules take `'page' | 'part'`. The outdated fallback needs no branch of its own: `cause` picks its copy, and it gets Reload page like the logic fallback. ```tsx 'use client'; import { Button } from '@project/island/atoms/button'; import { ErrorState } from '@project/island/molecules/error-state'; import { classifyError, describeError, handleError } from '@project/libs/error-handler'; import { useEffect, useRef } from 'react'; import { useTranslation } from 'react-i18next'; import { StatusEmptyState } from '../status-empty-state'; import { reloadOnce } from './reload-once'; import type { ErrorFallbackProps } from './types'; export function ErrorFallback({ error, size, name, onRetry }: ErrorFallbackProps) { const { t } = useTranslation('errors'); const headingRef = useRef(null); const { read, cause, retry } = classifyError(error); const islandSize = size === 'part' ? 'part' : 'page'; useEffect(() => { handleError(error, { where: size, name }); // Code from an older deploy: a failed page or app reloads into the current deploy. A part never does. if (retry === 'reload-page' && size !== 'part' && reloadOnce()) return; if (size !== 'part') headingRef.current?.focus(); }, [error, size, name, retry]); if (read === 'silent') return null; if (read !== 'boundary') return ; const { referenceId } = describeError(error, t); return ( {t('fallback.try-again')} ) : ( ) } /> ); } ``` `error-fallback/reload-once.ts`. `constants.ts` holds `OUTDATED_RELOAD_STORAGE_KEY = 'outdated-reload-at'` and `OUTDATED_RELOAD_WINDOW_MS = 60_000`. ```ts import { storage } from '@project/libs/local-storage'; import { OUTDATED_RELOAD_STORAGE_KEY, OUTDATED_RELOAD_WINDOW_MS } from './constants'; // At most one reload a minute, so a deploy that is still missing files shows the fallback instead of a reload loop. export function reloadOnce(): boolean { if (!navigator.onLine) return false; const last = storage.getJSON(OUTDATED_RELOAD_STORAGE_KEY); if (typeof last === 'number' && Date.now() - last < OUTDATED_RELOAD_WINDOW_MS) return false; storage.setJSON(OUTDATED_RELOAD_STORAGE_KEY, Date.now()); window.location.reload(); return true; } ``` `StatusEmptyState` (`error-boundaries/status-empty-state/`) renders island's `EmptyState` with the `errors:empty.` copy and, at page size, the link back. It is a client component, so the server page and parts can render it too. **Part boundary.** `app/error-boundaries/part-boundary/PartBoundary.tsx`. `PartBoundaryProps` is `{ name: string }`; `catchError` adds `children`. ```tsx 'use client'; import { useQueryErrorResetBoundary } from '@tanstack/react-query'; import { catchError, type ErrorInfo } from 'next/error'; import { ErrorFallback } from '../error-fallback'; import type { PartBoundaryProps } from './types'; function PartFallback({ name }: PartBoundaryProps, { error, retry, reset }: ErrorInfo) { const queryErrors = useQueryErrorResetBoundary(); const isServerError = 'digest' in error; return ( { queryErrors.reset(); if (isServerError) retry(); else reset(); }} /> ); } export const PartBoundary = catchError(PartFallback); ``` A part in a template: ```tsx }> ``` **Page and app boundaries.** `apps//src/app/(account)/error.tsx`: ```tsx 'use client'; import { ErrorFallback } from '@project//app/error-boundaries'; import { useQueryErrorResetBoundary } from '@tanstack/react-query'; type AccountErrorProps = { error: Error & { digest?: string }; retry: () => void }; export default function AccountError({ error, retry }: AccountErrorProps) { const queryErrors = useQueryErrorResetBoundary(); return ( <> { queryErrors.reset(); retry(); }} /> ); } ``` `apps//src/app/global-error.tsx`. `i18n` is the app's client i18n instance, so `useTranslation` works without providers. ```tsx 'use client'; import '../styles/app.css'; import { ErrorFallback } from '@project//app/error-boundaries'; import { i18n } from '../i18n'; export default function GlobalError({ error }: { error: Error & { digest?: string } }) { return ( window.location.reload()} /> ); } ``` The `AppShell` renders the one `Toaster`: ```tsx const { i18n } = useTranslation(); const dir = i18n.dir(); // in the returned JSX: ``` **Query client.** `configs/react-query.ts` keeps its `getQueryClient()` and dehydrate settings ([b2c-b2b.md](page-example.md)) and adds the lines below. ```ts import { handleError } from '@project/libs/error-handler'; import { defaultShouldDehydrateQuery, QueryCache, QueryClient } from '@tanstack/react-query'; function makeQueryClient(): QueryClient { return new QueryClient({ queryCache: new QueryCache({ onError: (error, query) => { if (query.state.data !== undefined) handleError(error, { where: 'refetch' }); }, }), defaultOptions: { queries: { staleTime: 60_000, retry: false, networkMode: 'offlineFirst', throwOnError: (_error, query) => query.state.data === undefined, }, mutations: { networkMode: 'offlineFirst' }, dehydrate: { shouldDehydrateQuery: (query) => defaultShouldDehydrateQuery(query) || query.state.status === 'pending', shouldRedactErrors: () => false, }, }, }); } ``` **Server reads.** `app/error-boundaries/read-on-server/read-on-server.ts`, exported only through the platform's `server.ts`. `types.ts` declares `ServerRead = { status: 'ok'; data: T } | { status: 'not-found' | 'no-access' }`. ```ts import 'server-only'; import { classifyError } from '@project/libs/error-handler'; import type { ServerRead } from './types'; export async function readOnServer(read: () => Promise): Promise> { try { return { status: 'ok', data: await read() }; } catch (error) { const outcome = classifyError(error).read; if (outcome === 'not-found' || outcome === 'no-access') return { status: outcome }; throw error; } } ``` `apps//src/app/(shop)/seller/[slug]/page.tsx`. A seller page is the same for every visitor, so it reads on the server. A page that depends on the viewer, such as an order page, loads in the browser instead, and its reads reach the fallback as browser errors ([rendering-patterns.md](rendering-patterns.md#auth-dependent-ui)). `getSeller` is a cache, so the metadata and the page share one request, and the cache keeps a failure for the request too. ```tsx import { StatusEmptyState } from '@project//app/error-boundaries'; import { getDevice, getSeller, readOnServer } from '@project//server'; import type { Metadata } from 'next'; import { notFound } from 'next/navigation'; import { SellerDesktop } from './templates/seller-desktop'; import { SellerMobile } from './templates/seller-mobile'; type SellerPageProps = { params: Promise<{ slug: string }> }; export async function generateMetadata({ params }: SellerPageProps): Promise { const { slug } = await params; const seller = await readOnServer(() => getSeller(slug)); if (seller.status !== 'ok') return { robots: { index: false } }; return { title: seller.data.name }; } export default async function SellerPage({ params }: SellerPageProps) { const { slug } = await params; const [device, seller] = await Promise.all([getDevice(), readOnServer(() => getSeller(slug))]); if (seller.status === 'not-found') notFound(); if (seller.status === 'no-access') return ; return device === 'mobile' ? : ; } ``` A server part, `.../seller/[slug]/organisms/seller-ratings/SellerRatings.tsx`: ```tsx import { StatusEmptyState } from '@project//app/error-boundaries'; import { getSellerRatings, readOnServer } from '@project//server'; import { RatingsSummary } from './components/ratings-summary'; import type { SellerRatingsProps } from './types'; export async function SellerRatings({ sellerId }: SellerRatingsProps) { const ratings = await readOnServer(() => getSellerRatings(sellerId)); if (ratings.status !== 'ok') return ; return ; } ``` **Actions.** `showActionError` and `applyServerErrors`, with a login model and a mutation that use them: [code-patterns.md](code-patterns.md#validation-model-and-server-errors).