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

12 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/<platform>/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'. The outdated fallback needs no branch of its own: cause picks its copy, and it gets Reload page like the logic fallback.

'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<HTMLHeadingElement>(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 <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>
        )
      }
    />
  );
}

error-fallback/reload-once.ts. constants.ts holds OUTDATED_RELOAD_STORAGE_KEY = 'outdated-reload-at' and OUTDATED_RELOAD_WINDOW_MS = 60_000.

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<number>(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.<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="seller-ratings">
  <Suspense fallback={<SellerRatingsSkeleton />}>
    <SellerRatings sellerId={seller.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 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). getSeller 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, 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:

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.