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

282 lines
10 KiB
Markdown

# 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/<platform>/src/`, as in [code-patterns.md](code-patterns.md). Each `error-boundaries/<name>/` 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<ErrorBoundaryProps, ErrorBoundaryState> {
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'`.
```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 type { ErrorFallbackProps } from './types';
export function ErrorFallback({ error, size, name, onRetry }: ErrorFallbackProps) {
const { t } = useTranslation('errors');
const headingRef = useRef<HTMLHeadingElement>(null);
const { read, cause } = classifyError(error);
const islandSize = size === 'part' ? 'part' : 'page';
useEffect(() => {
handleError(error, { where: size, name });
if (size !== 'part') headingRef.current?.focus();
}, [error, size, name]);
if (read === 'silent') return null;
if (read !== 'boundary') return <StatusEmptyState variant={read} size={islandSize} headingRef={headingRef} />;
const { referenceId } = describeError(error, t);
return (
<ErrorState
size={islandSize}
headingRef={headingRef}
title={t(`fallback.${cause}.title`)}
description={t(`fallback.${cause}.description`)}
referenceId={referenceId && t('fallback.reference', { referenceId })}
action={
cause === 'network' ? (
<Button onClick={onRetry}>{t('fallback.try-again')}</Button>
) : (
<Button onClick={() => window.location.reload()}>{t('fallback.reload')}</Button>
)
}
/>
);
}
```
`StatusEmptyState` (`error-boundaries/status-empty-state/`) renders island's `EmptyState` with the `errors:empty.<variant>` 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 (
<ErrorFallback
error={error}
size="part"
name={name}
onRetry={() => {
queryErrors.reset();
if (isServerError) retry();
else reset();
}}
/>
);
}
export const PartBoundary = catchError(PartFallback);
```
A part in a template:
```tsx
<PartBoundary name="seller-ratings">
<Suspense fallback={<SellerRatingsSkeleton />}>
<SellerRatings sellerId={seller.id} />
</Suspense>
</PartBoundary>
```
**Page and app boundaries.** `apps/<app>/src/app/(account)/error.tsx`:
```tsx
'use client';
import { ErrorFallback } from '@project/<platform>/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 (
<>
<meta name="robots" content="noindex" />
<ErrorFallback
error={error}
size="page"
onRetry={() => {
queryErrors.reset();
retry();
}}
/>
</>
);
}
```
`apps/<app>/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/<platform>/app/error-boundaries';
import { i18n } from '../i18n';
export default function GlobalError({ error }: { error: Error & { digest?: string } }) {
return (
<html lang={i18n.language} dir={i18n.dir()}>
<body>
<meta name="robots" content="noindex" />
<ErrorFallback error={error} size="app" onRetry={() => window.location.reload()} />
</body>
</html>
);
}
```
The `AppShell` renders the one `Toaster`:
```tsx
const { i18n } = useTranslation();
const dir = i18n.dir();
// in the returned JSX:
<Toaster dir={dir} position={dir === 'rtl' ? 'bottom-left' : 'bottom-right'} />
```
**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<T> = { 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<T>(read: () => Promise<T>): Promise<ServerRead<T>> {
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/<app>/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/<platform>/app/error-boundaries';
import { getDevice, getSeller, readOnServer } from '@project/<platform>/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<Metadata> {
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 <StatusEmptyState variant="no-access" size="page" />;
return device === 'mobile' ? <SellerMobile seller={seller.data} /> : <SellerDesktop seller={seller.data} />;
}
```
A server part, `.../seller/[slug]/organisms/seller-ratings/SellerRatings.tsx`:
```tsx
import { StatusEmptyState } from '@project/<platform>/app/error-boundaries';
import { getSellerRatings, readOnServer } from '@project/<platform>/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 <StatusEmptyState variant={ratings.status} size="part" />;
return <RatingsSummary ratings={ratings.data} />;
}
```
**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).