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

10 KiB

Error handling code

The code for 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/<app>/src/, as in 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[].

'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'.

'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.

'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:

<PartBoundary name="order-invoice">
  <Suspense fallback={<OrderInvoiceSkeleton />}>
    <OrderInvoice orderId={order.id} />
  </Suspense>
</PartBoundary>

Page and app boundaries. apps/<app>/src/app/(account)/error.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.

'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:

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) and adds the lines below.

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' }.

import 'server-only';
import { classifyError } from '@project/libs/error-handler';
import { isHttpError } from '@project/libs/http';
import { redirect } from 'next/navigation';
import { ROUTES } from '../../navigation';
import type { ServerRead } from './types';

export async function readOnServer<T>(
  read: () => Promise<T>,
  options: { returnTo?: string } = {},
): 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 };
    if (options.returnTo && isHttpError(error) && error.status === 401) {
      redirect(`${ROUTES.login}?redirect=${encodeURIComponent(options.returnTo)}`);
    }
    throw error;
  }
}

apps/<app>/src/app/(account)/orders/[id]/page.tsx. getOrder is a cache, so the metadata and the page share one request, and the cache keeps a failure for the request too.

import { StatusEmptyState } from '@project/<platform>/app/error-boundaries';
import { getDevice, getOrder, readOnServer } from '@project/<platform>/server';
import type { Metadata } from 'next';
import { notFound } from 'next/navigation';
import { OrderDesktop } from './templates/order-desktop';
import { OrderMobile } from './templates/order-mobile';

type OrderPageProps = { params: Promise<{ id: string }> };

export async function generateMetadata({ params }: OrderPageProps): Promise<Metadata> {
  const { id } = await params;
  const order = await readOnServer(() => getOrder(id));
  if (order.status !== 'ok') return { robots: { index: false } };
  return { title: order.data.title };
}

export default async function OrderPage({ params }: OrderPageProps) {
  const { id } = await params;
  const [device, order] = await Promise.all([
    getDevice(),
    readOnServer(() => getOrder(id), { returnTo: `/orders/${id}` }),
  ]);
  if (order.status === 'not-found') notFound();
  if (order.status === 'no-access') return <StatusEmptyState variant="no-access" size="page" />;
  return device === 'mobile' ? <OrderMobile order={order.data} /> : <OrderDesktop order={order.data} />;
}

A server part, .../orders/[id]/organisms/order-invoice/OrderInvoice.tsx:

import { StatusEmptyState } from '@project/<platform>/app/error-boundaries';
import { getOrderInvoice, readOnServer } from '@project/<platform>/server';
import { InvoiceSummary } from './components/invoice-summary';
import type { OrderInvoiceProps } from './types';

export async function OrderInvoice({ orderId }: OrderInvoiceProps) {
  const invoice = await readOnServer(() => getOrderInvoice(orderId));
  if (invoice.status !== 'ok') return <StatusEmptyState variant={invoice.status} size="part" />;
  return <InvoiceSummary invoice={invoice.data} />;
}

Actions. showActionError and applyServerErrors, with a login model and a mutation that use them: code-patterns.md.