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

13 KiB

Error handler lib (packages/libs/src/error-handler)

Four functions that every project uses to decide what an error shows, what it says, and whether it is reported: configureErrorHandler, classifyError, describeError, and handleError. The model they implement (error boundaries, API errors by status, empty states) is in error-handling.md.

It is framework-agnostic (no React, Next.js, TanStack, i18next, or sonner imports), runs in the browser and on the server, and has no dependency. It imports only isHttpError from the HTTP lib (lib-http.md). It never shows anything: boundaries, empty states, and toasts live in the apps and platforms.

Contents: Structure · Types · API · Classification · Messages and reference ID · Reporting · Implementation · Usage · Acceptance checklist

Structure

packages/libs/src/error-handler/
├── error-handler.ts   # configureErrorHandler, classifyError, describeError, handleError
├── types.ts           # ErrorClass and its unions, ErrorContext, ErrorReport, ErrorHandlerConfig, TranslateFn, ErrorDescription
├── constants.ts       # NOT_FOUND_STATUSES, LIB_MESSAGE_PREFIX, RETRY_AFTER_HINT_KEY
└── index.ts
  • index.ts exports the four functions and the types. Nothing goes in server.ts: the lib has no server-only capability, so both sides import it from index.ts.
  • Import by subpath: import { classifyError } from '@project/libs/error-handler'.

Types

type ErrorCause = 'network' | 'logic'; // network: the API or the connection failed, retry helps; logic: a bug, retry rarely helps
type ReadOutcome = 'silent' | 'not-found' | 'no-access' | 'boundary'; // what a failed read shows
type ActionOutcome = 'silent' | 'toast'; // what a failed action shows
type RetryKind = 'again' | 'wait' | 'reload' | 'fix' | 'none';

interface ErrorClass {
  cause: ErrorCause;
  read: ReadOutcome;
  action: ActionOutcome;
  retry: RetryKind;
  report: boolean; // true for 5xx and logic errors
}

type ErrorWhere = 'app' | 'page' | 'part' | 'action' | 'refetch' | 'server';

interface ErrorContext {
  where: ErrorWhere; // where the error stopped
  name?: string; // the part, action, or route, e.g. 'order-invoice'; never personal data
}

interface ErrorReport extends Partial<ErrorContext> {
  error: unknown;
  status?: number;
  code?: string;
  requestId?: string;
  digest?: string; // Next.js's id for a server error
}

interface ErrorHandlerConfig {
  report?: (report: ErrorReport) => void; // the error-tracking integration's adapter
  onForbidden?: () => void; // runs on every 403 that handleError handles
}

type TranslateFn = (key: string, options?: Record<string, unknown>) => string; // i18next's t fits

interface ErrorDescription {
  message?: string; // what went wrong, only when the user can understand it
  hint?: string; // how to fix it: the guide
  referenceId?: string; // requestId, or the server digest
}

API

  • configureErrorHandler(config): once per module graph, in the app's browser bootstrap (bootstrap.client.ts) and in instrumentation.ts's register() for the server. It merges config into the stored settings, so calling it again is safe. Libs never read env; the bootstrap passes everything in.
  • classifyError(error): ErrorClass: pure. It decides from the status first, then the code (table below). Anything that isn't an HttpError is a logic error, except a server error that reached the browser with only its digest.
  • describeError(error, t): ErrorDescription: the words for a toast or a fallback. Only strings that start with errors: go through t: those are the keys the HTTP lib creates. Server messages and hints arrive translated and pass through as they are.
  • handleError(error, context?): ErrorClass: call it once, where the error stops (the fallback that renders it, the toast that shows it, the refetch that swallows it, or the server's onRequestError). It classifies the error, sends a report when report is true, runs onForbidden on a 403, and returns the class. It never throws: a failing reporter or callback is swallowed, so handling an error never causes a second one.

Classification

The first matching row wins.

Error cause read action retry report
ABORTED network silent silent none no
401 network silent silent none no
403 network no-access toast none no
404, 410 network not-found toast reload no
409 network boundary toast reload no
429 network boundary toast wait no
5xx network boundary toast again yes
Other 4xx (400, 408, 422, …) network boundary toast fix no
NETWORK_ERROR, TIMEOUT network boundary toast again no
PARSE_ERROR, INTERCEPTOR_ERROR, UNKNOWN logic boundary toast none yes
Not an HttpError, with a digest network boundary toast again no
Anything else logic boundary toast none yes
  • 401 never reaches the UI: the HTTP lib refreshes, and a failed refresh logs out (lib-http.md). The server has no refresh, so server code checks for 401 itself and redirects to login (error-handling.md).
  • A digest without HttpError fields is a Server Component error seen in the browser: Next.js sends only the digest in production, so the browser can't classify it. The server already classified and reported it, and a retry renders the part again on the server.
  • Retry kinds: again offers a button that runs the same thing again; wait offers none and the hint says how long; reload offers a button that loads the latest data first; fix offers none, because the user must change the input; none offers none.

Messages and reference ID

  • message is set for 4xx statuses (the back end localizes them from Accept-Language) and for NETWORK_ERROR and TIMEOUT (the lib's errors: keys). It is left out for 5xx and logic errors, whose text means nothing to users and can leak internals.
  • hint is the error's hint. When there is none and the error has retryAfter, it is t('errors:http.retry-after', { seconds }).
  • referenceId is requestId, or the digest when there is no request id. Support finds the report by either.

Reporting

  • Reports go only to the report callback that the bootstrap passes in, never to an event on the event emitter.
  • report is true for 5xx and logic errors. 4xx, network, and timeout failures are the user's or the connection's, so they aren't reported; the HTTP lib's breadcrumbs keep them visible in the tracker when a reported error follows.
  • An ErrorReport carries the error, the context, and the status, code, request id, and digest, so the tracker can group by status and code and search by reference ID. It never carries form values, cookies, or headers.

Implementation

error-handler.ts, the parts that decide. constants.ts holds NOT_FOUND_STATUSES: readonly number[] = [404, 410], LIB_MESSAGE_PREFIX = 'errors:', and RETRY_AFTER_HINT_KEY = 'errors:http.retry-after'.

import { isHttpError } from '../http';
import { LIB_MESSAGE_PREFIX, NOT_FOUND_STATUSES, RETRY_AFTER_HINT_KEY } from './constants';
import type {
  ErrorClass,
  ErrorContext,
  ErrorDescription,
  ErrorHandlerConfig,
  ReadOutcome,
  RetryKind,
  TranslateFn,
} from './types';

let config: ErrorHandlerConfig = {};

export function configureErrorHandler(next: ErrorHandlerConfig): void {
  config = { ...config, ...next };
}

const SILENT: ErrorClass = { cause: 'network', read: 'silent', action: 'silent', retry: 'none', report: false };
const LOGIC: ErrorClass = { cause: 'logic', read: 'boundary', action: 'toast', retry: 'none', report: true };

function apiError(read: ReadOutcome, retry: RetryKind, report = false): ErrorClass {
  return { cause: 'network', read, action: 'toast', retry, report };
}

function getDigest(error: unknown): string | undefined {
  if (typeof error !== 'object' || error === null || !('digest' in error)) return undefined;
  return typeof error.digest === 'string' ? error.digest : undefined;
}

export function classifyError(error: unknown): ErrorClass {
  if (!isHttpError(error)) return getDigest(error) ? apiError('boundary', 'again') : LOGIC;
  const { status, code } = error;
  if (code === 'ABORTED' || status === 401) return SILENT;
  if (status === 403) return apiError('no-access', 'none');
  if (NOT_FOUND_STATUSES.includes(status)) return apiError('not-found', 'reload');
  if (status === 409) return apiError('boundary', 'reload');
  if (status === 429) return apiError('boundary', 'wait');
  if (status >= 500) return apiError('boundary', 'again', true);
  if (status >= 400) return apiError('boundary', 'fix');
  if (code === 'NETWORK_ERROR' || code === 'TIMEOUT') return apiError('boundary', 'again');
  return LOGIC;
}

export function describeError(error: unknown, t: TranslateFn): ErrorDescription {
  if (!isHttpError(error)) return { referenceId: getDigest(error) };
  const translate = (text?: string) => (text?.startsWith(LIB_MESSAGE_PREFIX) ? t(text) : text);
  const isUserFacing =
    (error.status >= 400 && error.status < 500) || error.code === 'NETWORK_ERROR' || error.code === 'TIMEOUT';
  return {
    message: isUserFacing ? translate(error.message) : undefined,
    hint:
      translate(error.hint) ??
      (error.retryAfter ? t(RETRY_AFTER_HINT_KEY, { seconds: error.retryAfter }) : undefined),
    referenceId: error.requestId ?? getDigest(error),
  };
}

export function handleError(error: unknown, context?: ErrorContext): ErrorClass {
  const errorClass = classifyError(error);
  try {
    if (errorClass.report) {
      config.report?.({
        ...context,
        error,
        status: isHttpError(error) ? error.status : undefined,
        code: isHttpError(error) ? error.code : undefined,
        requestId: isHttpError(error) ? error.requestId : undefined,
        digest: getDigest(error),
      });
    }
    if (isHttpError(error) && error.status === 403) config.onForbidden?.();
  } catch {
    // Handling an error must never throw a second one.
  }
  return errorClass;
}
  • config is startup configuration, set by the bootstrap, so module scope is allowed to hold it on the server (design-patterns.md). It never holds errors or anything per request.
  • On the server, onRequestError sees the real HttpError, with the digest Next.js gave it, so the report has both ids and matches what the browser shows.

Usage

Browser bootstrap (bootstrap.client.ts). The Sentry integration adapts ErrorReport to its vendor's event.

import { captureError } from '@project/integrations/sentry';
import { configureErrorHandler } from '@project/libs/error-handler';

configureErrorHandler({ report: captureError });

Server, apps/<app>/src/instrumentation.ts. register() runs once when the server starts, and onRequestError runs for every error that no server code caught.

import { captureServerError } from '@project/integrations/server';
import { configureErrorHandler, handleError } from '@project/libs/error-handler';
import type { Instrumentation } from 'next';

export function register(): void {
  configureErrorHandler({ report: captureServerError });
}

export const onRequestError: Instrumentation.onRequestError = (error, _request, context) => {
  handleError(error, { where: 'server', name: context.routePath });
};

Where the other calls go, with code, is in error-handling.md: ErrorFallback classifies, describes, and handles what reaches a boundary; showActionError does the same for actions; the query client's QueryCache.onError handles failed refetches.

Acceptance checklist

For building or changing the lib:

[ ] Every row of the classification table returns its class, with status checked before code
[ ] ABORTED and 401 are silent for reads and actions; 403 runs onForbidden once per handleError call
[ ] A plain Error is a reported logic error; an object with only a digest is a network error that isn't reported
[ ] describeError translates only errors:-prefixed strings; server messages pass through unchanged
[ ] describeError leaves out the message for 5xx and logic errors and keeps it for 4xx, network, and timeout
[ ] A 429 or 503 with retryAfter and no hint gets the retry-after hint with its seconds
[ ] referenceId is requestId, else digest
[ ] handleError reports 5xx and logic errors with status, code, requestId, and digest, and nothing else
[ ] handleError never throws, even when report or onForbidden throws
[ ] The lib imports nothing but the HTTP lib: no React, Next.js, TanStack, i18next, or sonner