@tcds-io/fastify-errors 0.0.0-stage → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,23 @@
1
- # Temporary Holding Version
1
+ # @tcds-io/fastify-errors
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Fastify error handler: maps [`@tcds-io/domain`](../domain) to an HTTP status and a wire body, in one place. `mapError` is the framework-free core, exported for other hosts.
4
+
5
+ ```ts
6
+ import { installErrorHandler, mapError } from '@tcds-io/fastify-errors';
7
+
8
+ installErrorHandler(app); // error handler + not-found handler, one wire shape
9
+ ```
10
+
11
+ Every failure leaves as `{ error: { id?, code, message, details?, trace? } }`.
12
+
13
+ - 4xx: `code`, `message`, `details?`; no `id`, not logged.
14
+ - 5xx: `code`, `message` = the status's HTTP reason (`Internal Server Error`, `Bad Gateway`, `Service Unavailable`, ...; one text for all with `internalMessage`), `id`. A thrown `ExternalPartyError` is a 502: the failure is a partner's, not ours. The real message and details never leave the process; log the error with the id. A `classify` result with `exposeMessage: true` keeps its own `message` on a 501-599 (a 502 `Payment provider unavailable`, say); details stay stripped and the `id` stays. A 500 always says `internalMessage`.
15
+ - Request schema failures (Fastify validation or a thrown `ZodError`, zod 3 or 4, matched by shape) are a 400 `REQUEST_INVALID` with `details.issues: [{ path: 'a.0.b', code, message }]`.
16
+ - Fastify's own request errors (`FST_ERR_CTP_*`, `FST_ERR_BAD_URL`, …) come from `DEFAULT_FRAMEWORK_ERRORS`; override entries with `frameworkErrors`.
17
+ - `retry-after` is set for a rate limit that knows its delay. Any other framework 4xx `statusCode` keeps its status as `BAD_REQUEST`.
18
+ - Options: `statusTable` (first match wins), `classify` (runs first, for legacy classes), `errorId`, `unknownCode`, `validationCode`, `clientErrorCode`, `internalMessage`, `includeTrace` (dev only).
19
+ - `installErrorHandler(app, { onError, routeNotFoundCode })`: `onError` sees every failure (status, body, issues, error, request) and replaces the default 5xx log line. `createErrorHandler(options)` is the bare handler, for Fastify's `frameworkErrors` option.
20
+
21
+ ## Peers
22
+
23
+ `@tcds-io/domain` and `fastify` are peer dependencies: install `@tcds-io/domain` yourself so the app has one copy (ADR-0070).
@@ -0,0 +1,4 @@
1
+ export { DEFAULT_FRAMEWORK_ERRORS, DEFAULT_STATUS_TABLE, mapError } from './map-error.js';
2
+ export type { Classification, ErrorClass, FrameworkErrorTable, MappedError, MapErrorOptions, StatusTable, WireBody, WireError, WireIssue, } from './map-error.js';
3
+ export { createErrorHandler, installErrorHandler } from './plugin.js';
4
+ export type { ErrorEvent, ErrorHandlerOptions } from './plugin.js';
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { DEFAULT_FRAMEWORK_ERRORS, DEFAULT_STATUS_TABLE, mapError } from './map-error.js';
2
+ export { createErrorHandler, installErrorHandler } from './plugin.js';
@@ -0,0 +1,86 @@
1
+ export type ErrorClass = abstract new (...args: never[]) => Error;
2
+ /** First match wins, so list a subclass before its parent (`RefusedByExternalPartyError` is covered by its parent's 502). */
3
+ export type StatusTable = ReadonlyArray<readonly [ErrorClass, number]>;
4
+ export declare const DEFAULT_STATUS_TABLE: StatusTable;
5
+ /** One failing field of a request: a dotted path (`items.0.name`), the validator's code and its message. */
6
+ export type WireIssue = {
7
+ readonly path: string;
8
+ readonly code: string;
9
+ readonly message: string;
10
+ };
11
+ export type WireError = {
12
+ /** Present on 5xx only: quote it to support, find the log line with it. */
13
+ readonly id?: string;
14
+ readonly code: string;
15
+ readonly message: string;
16
+ readonly details?: Readonly<Record<string, unknown>>;
17
+ /** The stack, one line per entry. Only with `includeTrace`: never in production. */
18
+ readonly trace?: readonly string[];
19
+ };
20
+ /** Every failure leaves as `{ error: { ... } }`. */
21
+ export type WireBody = {
22
+ readonly error: WireError;
23
+ };
24
+ /** What a classifier decides for an error. */
25
+ export type Classification = {
26
+ readonly status: number;
27
+ readonly code: string;
28
+ readonly message?: string;
29
+ readonly details?: Readonly<Record<string, unknown>>;
30
+ readonly headers?: Readonly<Record<string, string>>;
31
+ /**
32
+ * Send `message` on a 501-599 instead of `internalMessage`. Default false. For a failure we name on purpose, such
33
+ * as a 502 `Payment provider unavailable`. Ignored on a 500, which always says `internalMessage`, and without a
34
+ * `message`. Details stay stripped and the `id` is still minted.
35
+ */
36
+ readonly exposeMessage?: boolean;
37
+ };
38
+ /** A Fastify error code (`FST_ERR_*`) and what it answers. */
39
+ export type FrameworkErrorTable = Readonly<Record<string, {
40
+ readonly status: number;
41
+ readonly code: string;
42
+ readonly message: string;
43
+ }>>;
44
+ /** Fastify's request failures that are the caller's fault. Override any entry through `frameworkErrors`. */
45
+ export declare const DEFAULT_FRAMEWORK_ERRORS: FrameworkErrorTable;
46
+ export type MappedError = {
47
+ readonly status: number;
48
+ readonly body: WireBody;
49
+ /** Log it. True for 5xx; a 4xx is the caller's mistake and stays quiet. */
50
+ readonly log: boolean;
51
+ /** Response headers the status implies, such as `retry-after`. */
52
+ readonly headers: Readonly<Record<string, string>>;
53
+ /** The failing fields of a validation failure, for reporting. Empty otherwise. */
54
+ readonly issues: readonly WireIssue[];
55
+ };
56
+ export type MapErrorOptions = {
57
+ /** Replaces the default table, or extend it: `[[MyError, 410], ...DEFAULT_STATUS_TABLE]`. */
58
+ readonly statusTable?: StatusTable;
59
+ /** Runs first. Return a classification to take over an error (a legacy class, say), `undefined` to fall through. */
60
+ readonly classify?: (error: unknown) => Classification | undefined;
61
+ /** Mints the id of a 5xx. Default: a random UUID. */
62
+ readonly errorId?: () => string;
63
+ /** Wire `code` of anything that is not an `AppError`. Default `INTERNAL_ERROR`. */
64
+ readonly unknownCode?: string;
65
+ /** Wire `code` of a framework client error not in `frameworkErrors`. Default `BAD_REQUEST`. */
66
+ readonly clientErrorCode?: string;
67
+ /** Wire `code` of a request that failed its schema (Fastify validation or a thrown `ZodError`). Default `REQUEST_INVALID`. */
68
+ readonly validationCode?: string;
69
+ /** Merged over `DEFAULT_FRAMEWORK_ERRORS`, keyed by Fastify error code. */
70
+ readonly frameworkErrors?: FrameworkErrorTable;
71
+ /** What every 5xx says instead of its real message. Default: the status's HTTP reason (`Internal Server Error`, `Bad Gateway`, ...). */
72
+ readonly internalMessage?: string;
73
+ /** Adds the stack as `trace`. For local development only. */
74
+ readonly includeTrace?: boolean;
75
+ };
76
+ /**
77
+ * The one place an error becomes an HTTP status and a wire body `{ error: { id?, code, message, details?, trace? } }`.
78
+ * Framework-free: hand the result to your framework's error hook.
79
+ *
80
+ * - 4xx: the message and details go out, there is no id, and `log` is false.
81
+ * - 5xx: the status's HTTP reason (or `internalMessage`), no details, and an `id`; `log` is true so the hook logs the real error once with it.
82
+ * A classification with `exposeMessage: true` keeps its own message on a 501-599; a 500 never does.
83
+ * - Order: `classify`, then the status table for an `AppError`, then a request schema failure (400 with
84
+ * `details.issues`), then a known Fastify error code, then any framework 4xx `statusCode`, then 500.
85
+ */
86
+ export declare const mapError: (error: unknown, options?: MapErrorOptions) => MappedError;
@@ -0,0 +1,118 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { STATUS_CODES } from 'node:http';
3
+ import { AppError, BusinessRuleError, ConflictError, ExternalPartyError, ForbiddenError, NotFoundError, NotImplementedError, RateLimitedError, UnauthenticatedError, UnavailableError, ValidationError, } from '@tcds-io/domain';
4
+ export const DEFAULT_STATUS_TABLE = [
5
+ [ValidationError, 400],
6
+ [UnauthenticatedError, 401],
7
+ [ForbiddenError, 403],
8
+ [NotFoundError, 404],
9
+ [ConflictError, 409],
10
+ [BusinessRuleError, 422],
11
+ [RateLimitedError, 429],
12
+ [NotImplementedError, 501],
13
+ [ExternalPartyError, 502],
14
+ [UnavailableError, 503],
15
+ ];
16
+ /** Fastify's request failures that are the caller's fault. Override any entry through `frameworkErrors`. */
17
+ export const DEFAULT_FRAMEWORK_ERRORS = {
18
+ FST_ERR_CTP_INVALID_MEDIA_TYPE: { status: 415, code: 'UNSUPPORTED_MEDIA_TYPE', message: 'Unsupported media type' },
19
+ FST_ERR_CTP_EMPTY_JSON_BODY: { status: 400, code: 'MALFORMED_BODY', message: 'Request body could not be parsed' },
20
+ FST_ERR_CTP_INVALID_JSON_BODY: { status: 400, code: 'MALFORMED_BODY', message: 'Request body could not be parsed' },
21
+ FST_ERR_CTP_INVALID_CONTENT_LENGTH: { status: 400, code: 'MALFORMED_BODY', message: 'Request body could not be parsed' },
22
+ FST_ERR_BAD_URL: { status: 400, code: 'MALFORMED_URL', message: 'Request URL is malformed' },
23
+ FST_ERR_CTP_BODY_TOO_LARGE: { status: 413, code: 'BODY_TOO_LARGE', message: 'Request body is too large' },
24
+ FST_ERR_MAX_PARAM_LENGTH: { status: 414, code: 'URI_TOO_LONG', message: 'Request URI is too long' },
25
+ };
26
+ const VALIDATION_MESSAGE = 'Request validation failed';
27
+ const fieldOf = (value, key) => typeof value === 'object' && value !== null && key in value ? value[key] : undefined;
28
+ const stringOr = (value, fallback) => (typeof value === 'string' ? value : fallback);
29
+ const clientStatusOf = (error) => {
30
+ const status = fieldOf(error, 'statusCode');
31
+ return typeof status === 'number' && status >= 400 && status < 500 ? status : null;
32
+ };
33
+ const messageOf = (error) => (error instanceof Error ? error.message : 'Unknown error');
34
+ /** Fastify's own schema failure: `validation` holds one entry per failing keyword, with a JSON pointer. */
35
+ const fastifyIssuesOf = (error) => {
36
+ const validation = fieldOf(error, 'validation');
37
+ if (!Array.isArray(validation))
38
+ return null;
39
+ return validation.map((entry) => ({
40
+ path: stringOr(fieldOf(entry, 'instancePath'), '').replace(/^\//, '').replaceAll('/', '.'),
41
+ code: stringOr(fieldOf(entry, 'keyword'), 'invalid'),
42
+ message: stringOr(fieldOf(entry, 'message'), ''),
43
+ }));
44
+ };
45
+ /**
46
+ * A `ZodError` thrown in a handler, matched by shape so zod stays out of the dependencies.
47
+ * No `instanceof Error`: zod 4's `ZodError` is not an `Error` instance.
48
+ */
49
+ const zodIssuesOf = (error) => {
50
+ const issues = fieldOf(error, 'issues');
51
+ if (fieldOf(error, 'name') !== 'ZodError' || !Array.isArray(issues))
52
+ return null;
53
+ return issues.map((issue) => {
54
+ const path = fieldOf(issue, 'path');
55
+ return {
56
+ path: Array.isArray(path) ? path.map(String).join('.') : '',
57
+ code: stringOr(fieldOf(issue, 'code'), 'invalid'),
58
+ message: stringOr(fieldOf(issue, 'message'), ''),
59
+ };
60
+ });
61
+ };
62
+ const issuesOfDetails = (details) => {
63
+ const issues = details?.['issues'];
64
+ return Array.isArray(issues) ? issues.filter((issue) => typeof fieldOf(issue, 'path') === 'string') : [];
65
+ };
66
+ const traceOf = (error) => error instanceof Error && typeof error.stack === 'string' && error.stack.length > 0 ? error.stack.split('\n').map((line) => line.trimEnd()) : undefined;
67
+ const retryAfterOf = (error) => error instanceof RateLimitedError && error.retryAfterMs !== undefined ? { 'retry-after': String(Math.ceil(error.retryAfterMs / 1000)) } : {};
68
+ const classifyBuiltIn = (error, options) => {
69
+ if (error instanceof AppError) {
70
+ const status = (options.statusTable ?? DEFAULT_STATUS_TABLE).find(([type]) => error instanceof type)?.[1] ?? 500;
71
+ return { status, code: error.code, message: error.message, ...(error.details !== undefined ? { details: error.details } : {}), headers: retryAfterOf(error) };
72
+ }
73
+ const issues = fastifyIssuesOf(error) ?? zodIssuesOf(error);
74
+ if (issues !== null) {
75
+ return { status: 400, code: options.validationCode ?? 'REQUEST_INVALID', message: VALIDATION_MESSAGE, details: { issues } };
76
+ }
77
+ const frameworkCode = fieldOf(error, 'code');
78
+ const frameworkErrors = { ...DEFAULT_FRAMEWORK_ERRORS, ...options.frameworkErrors };
79
+ const known = typeof frameworkCode === 'string' && Object.hasOwn(frameworkErrors, frameworkCode) ? frameworkErrors[frameworkCode] : undefined;
80
+ if (known !== undefined)
81
+ return known;
82
+ const clientStatus = clientStatusOf(error);
83
+ if (clientStatus !== null) {
84
+ return { status: clientStatus, code: options.clientErrorCode ?? 'BAD_REQUEST', message: messageOf(error) };
85
+ }
86
+ return { status: 500, code: options.unknownCode ?? 'INTERNAL_ERROR' };
87
+ };
88
+ /**
89
+ * The one place an error becomes an HTTP status and a wire body `{ error: { id?, code, message, details?, trace? } }`.
90
+ * Framework-free: hand the result to your framework's error hook.
91
+ *
92
+ * - 4xx: the message and details go out, there is no id, and `log` is false.
93
+ * - 5xx: the status's HTTP reason (or `internalMessage`), no details, and an `id`; `log` is true so the hook logs the real error once with it.
94
+ * A classification with `exposeMessage: true` keeps its own message on a 501-599; a 500 never does.
95
+ * - Order: `classify`, then the status table for an `AppError`, then a request schema failure (400 with
96
+ * `details.issues`), then a known Fastify error code, then any framework 4xx `statusCode`, then 500.
97
+ */
98
+ export const mapError = (error, options = {}) => {
99
+ const classification = options.classify?.(error) ?? classifyBuiltIn(error, options);
100
+ const { status } = classification;
101
+ const server = status >= 500;
102
+ const trace = options.includeTrace === true ? traceOf(error) : undefined;
103
+ const details = server ? undefined : classification.details;
104
+ const internal = options.internalMessage ?? STATUS_CODES[status] ?? 'Internal Server Error';
105
+ const message = !server
106
+ ? (classification.message ?? messageOf(error))
107
+ : status !== 500 && classification.exposeMessage === true && classification.message !== undefined
108
+ ? classification.message
109
+ : internal;
110
+ const wire = {
111
+ ...(server ? { id: (options.errorId ?? randomUUID)() } : {}),
112
+ code: classification.code,
113
+ message,
114
+ ...(details !== undefined ? { details } : {}),
115
+ ...(trace !== undefined ? { trace } : {}),
116
+ };
117
+ return { status, body: { error: wire }, log: server, headers: classification.headers ?? {}, issues: issuesOfDetails(details) };
118
+ };
@@ -0,0 +1,23 @@
1
+ import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
2
+ import { type MapErrorOptions, type MappedError } from './map-error.js';
3
+ /** What `onError` sees: the raw error, the request, and what is about to be sent. */
4
+ export type ErrorEvent = MappedError & {
5
+ readonly error: unknown;
6
+ readonly request: FastifyRequest;
7
+ };
8
+ export type ErrorHandlerOptions = MapErrorOptions & {
9
+ /**
10
+ * Called for every failure before the reply is sent: report it, count it, alert. When set it replaces the default,
11
+ * which logs a 5xx on `request.log` with its id, so log there yourself.
12
+ */
13
+ readonly onError?: (event: ErrorEvent) => void;
14
+ /** Wire `code` of an unknown route. Default `ROUTE_NOT_FOUND`. */
15
+ readonly routeNotFoundCode?: string;
16
+ };
17
+ /**
18
+ * The handler on its own, for places Fastify does not route through `setErrorHandler`, such as `frameworkErrors` in
19
+ * the Fastify factory options (errors raised before the request hooks ran).
20
+ */
21
+ export declare const createErrorHandler: (options?: ErrorHandlerOptions) => (error: unknown, request: FastifyRequest, reply: FastifyReply) => FastifyReply;
22
+ /** Sets the Fastify error handler and the not-found handler so every failure leaves as `{ error: { ... } }`. */
23
+ export declare const installErrorHandler: (app: FastifyInstance, options?: ErrorHandlerOptions) => void;
package/dist/plugin.js ADDED
@@ -0,0 +1,23 @@
1
+ import { mapError } from './map-error.js';
2
+ const defaultOnError = ({ log, error, request, body }) => {
3
+ if (log)
4
+ request.log.error({ err: error, errorId: body.error.id }, 'request failed');
5
+ };
6
+ /**
7
+ * The handler on its own, for places Fastify does not route through `setErrorHandler`, such as `frameworkErrors` in
8
+ * the Fastify factory options (errors raised before the request hooks ran).
9
+ */
10
+ export const createErrorHandler = (options = {}) => (error, request, reply) => {
11
+ const mapped = mapError(error, options);
12
+ (options.onError ?? defaultOnError)({ ...mapped, error, request });
13
+ return reply.code(mapped.status).headers(mapped.headers).send(mapped.body);
14
+ };
15
+ /** Sets the Fastify error handler and the not-found handler so every failure leaves as `{ error: { ... } }`. */
16
+ export const installErrorHandler = (app, options = {}) => {
17
+ app.setErrorHandler(createErrorHandler(options));
18
+ app.setNotFoundHandler((request, reply) => {
19
+ return reply
20
+ .code(404)
21
+ .send({ error: { code: options.routeNotFoundCode ?? 'ROUTE_NOT_FOUND', message: `Route ${request.method} ${request.url} not found` } });
22
+ });
23
+ };
package/package.json CHANGED
@@ -1,6 +1,46 @@
1
1
  {
2
2
  "name": "@tcds-io/fastify-errors",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.2",
4
+ "description": "Fastify error handler: maps @tcds-io/domain errors to an HTTP status and a wire body in one place.",
5
+ "type": "module",
6
+ "sideEffects": false,
7
+ "license": "MIT",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/tcds-io/ts-platform.git",
11
+ "directory": "packages/fastify-errors"
12
+ },
13
+ "publishConfig": {
14
+ "access": "public",
15
+ "registry": "https://registry.npmjs.org"
16
+ },
17
+ "files": [
18
+ "dist"
19
+ ],
20
+ "exports": {
21
+ ".": {
22
+ "types": "./dist/index.d.ts",
23
+ "import": "./dist/index.js"
24
+ }
25
+ },
26
+ "devDependencies": {
27
+ "@types/node": "^22.10.2",
28
+ "fastify": "^5.6.0",
29
+ "typescript": "^5.7.2",
30
+ "vitest": "^2.1.8",
31
+ "zod": "^4.1.0",
32
+ "@tcds-io/domain": "^0.1.0"
33
+ },
34
+ "engines": {
35
+ "node": ">=22"
36
+ },
37
+ "peerDependencies": {
38
+ "@tcds-io/domain": "~0.1.0",
39
+ "fastify": ">=5"
40
+ },
41
+ "scripts": {
42
+ "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.build.json",
43
+ "check:types": "tsc --noEmit -p .",
44
+ "test": "vitest run"
45
+ }
6
46
  }