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

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/errors`](../errors) 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: 'Internal error'`, `id`. The real message and details never leave the process; log the error with the id.
15
+ - Request schema failures (Fastify validation or a thrown `ZodError`) 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/errors` and `fastify` are peer dependencies: install `@tcds-io/errors` 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,79 @@
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
+ /** A Fastify error code (`FST_ERR_*`) and what it answers. */
33
+ export type FrameworkErrorTable = Readonly<Record<string, {
34
+ readonly status: number;
35
+ readonly code: string;
36
+ readonly message: string;
37
+ }>>;
38
+ /** Fastify's request failures that are the caller's fault. Override any entry through `frameworkErrors`. */
39
+ export declare const DEFAULT_FRAMEWORK_ERRORS: FrameworkErrorTable;
40
+ export type MappedError = {
41
+ readonly status: number;
42
+ readonly body: WireBody;
43
+ /** Log it. True for 5xx; a 4xx is the caller's mistake and stays quiet. */
44
+ readonly log: boolean;
45
+ /** Response headers the status implies, such as `retry-after`. */
46
+ readonly headers: Readonly<Record<string, string>>;
47
+ /** The failing fields of a validation failure, for reporting. Empty otherwise. */
48
+ readonly issues: readonly WireIssue[];
49
+ };
50
+ export type MapErrorOptions = {
51
+ /** Replaces the default table, or extend it: `[[MyError, 410], ...DEFAULT_STATUS_TABLE]`. */
52
+ readonly statusTable?: StatusTable;
53
+ /** Runs first. Return a classification to take over an error (a legacy class, say), `undefined` to fall through. */
54
+ readonly classify?: (error: unknown) => Classification | undefined;
55
+ /** Mints the id of a 5xx. Default: a random UUID. */
56
+ readonly errorId?: () => string;
57
+ /** Wire `code` of anything that is not an `AppError`. Default `INTERNAL_ERROR`. */
58
+ readonly unknownCode?: string;
59
+ /** Wire `code` of a framework client error not in `frameworkErrors`. Default `BAD_REQUEST`. */
60
+ readonly clientErrorCode?: string;
61
+ /** Wire `code` of a request that failed its schema (Fastify validation or a thrown `ZodError`). Default `REQUEST_INVALID`. */
62
+ readonly validationCode?: string;
63
+ /** Merged over `DEFAULT_FRAMEWORK_ERRORS`, keyed by Fastify error code. */
64
+ readonly frameworkErrors?: FrameworkErrorTable;
65
+ /** What a 5xx says instead of its real message. Default `Internal error`. */
66
+ readonly internalMessage?: string;
67
+ /** Adds the stack as `trace`. For local development only. */
68
+ readonly includeTrace?: boolean;
69
+ };
70
+ /**
71
+ * The one place an error becomes an HTTP status and a wire body `{ error: { id?, code, message, details?, trace? } }`.
72
+ * Framework-free: hand the result to your framework's error hook.
73
+ *
74
+ * - 4xx: the message and details go out, there is no id, and `log` is false.
75
+ * - 5xx: a generic message, no details, and an `id`; `log` is true so the hook logs the real error once with it.
76
+ * - Order: `classify`, then the status table for an `AppError`, then a request schema failure (400 with
77
+ * `details.issues`), then a known Fastify error code, then any framework 4xx `statusCode`, then 500.
78
+ */
79
+ export declare const mapError: (error: unknown, options?: MapErrorOptions) => MappedError;
@@ -0,0 +1,107 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { AppError, BusinessRuleError, ConflictError, ExternalPartyError, ForbiddenError, NotFoundError, NotImplementedError, RateLimitedError, UnauthenticatedError, UnavailableError, ValidationError, } from '@tcds-io/errors';
3
+ export const DEFAULT_STATUS_TABLE = [
4
+ [ValidationError, 400],
5
+ [UnauthenticatedError, 401],
6
+ [ForbiddenError, 403],
7
+ [NotFoundError, 404],
8
+ [ConflictError, 409],
9
+ [BusinessRuleError, 422],
10
+ [RateLimitedError, 429],
11
+ [NotImplementedError, 501],
12
+ [ExternalPartyError, 502],
13
+ [UnavailableError, 503],
14
+ ];
15
+ /** Fastify's request failures that are the caller's fault. Override any entry through `frameworkErrors`. */
16
+ export const DEFAULT_FRAMEWORK_ERRORS = {
17
+ FST_ERR_CTP_INVALID_MEDIA_TYPE: { status: 415, code: 'UNSUPPORTED_MEDIA_TYPE', message: 'Unsupported media type' },
18
+ FST_ERR_CTP_EMPTY_JSON_BODY: { status: 400, code: 'MALFORMED_BODY', message: 'Request body could not be parsed' },
19
+ FST_ERR_CTP_INVALID_JSON_BODY: { status: 400, code: 'MALFORMED_BODY', message: 'Request body could not be parsed' },
20
+ FST_ERR_CTP_INVALID_CONTENT_LENGTH: { status: 400, code: 'MALFORMED_BODY', message: 'Request body could not be parsed' },
21
+ FST_ERR_BAD_URL: { status: 400, code: 'MALFORMED_URL', message: 'Request URL is malformed' },
22
+ FST_ERR_CTP_BODY_TOO_LARGE: { status: 413, code: 'BODY_TOO_LARGE', message: 'Request body is too large' },
23
+ FST_ERR_MAX_PARAM_LENGTH: { status: 414, code: 'URI_TOO_LONG', message: 'Request URI is too long' },
24
+ };
25
+ const VALIDATION_MESSAGE = 'Request validation failed';
26
+ const fieldOf = (value, key) => typeof value === 'object' && value !== null && key in value ? value[key] : undefined;
27
+ const stringOr = (value, fallback) => (typeof value === 'string' ? value : fallback);
28
+ const clientStatusOf = (error) => {
29
+ const status = fieldOf(error, 'statusCode');
30
+ return typeof status === 'number' && status >= 400 && status < 500 ? status : null;
31
+ };
32
+ const messageOf = (error) => (error instanceof Error ? error.message : 'Unknown error');
33
+ /** Fastify's own schema failure: `validation` holds one entry per failing keyword, with a JSON pointer. */
34
+ const fastifyIssuesOf = (error) => {
35
+ const validation = fieldOf(error, 'validation');
36
+ if (!Array.isArray(validation))
37
+ return null;
38
+ return validation.map((entry) => ({
39
+ path: stringOr(fieldOf(entry, 'instancePath'), '').replace(/^\//, '').replaceAll('/', '.'),
40
+ code: stringOr(fieldOf(entry, 'keyword'), 'invalid'),
41
+ message: stringOr(fieldOf(entry, 'message'), ''),
42
+ }));
43
+ };
44
+ /** A `ZodError` thrown in a handler, matched by shape so zod stays out of the dependencies. */
45
+ const zodIssuesOf = (error) => {
46
+ const issues = fieldOf(error, 'issues');
47
+ if (!(error instanceof Error) || error.name !== 'ZodError' || !Array.isArray(issues))
48
+ return null;
49
+ return issues.map((issue) => {
50
+ const path = fieldOf(issue, 'path');
51
+ return {
52
+ path: Array.isArray(path) ? path.map(String).join('.') : '',
53
+ code: stringOr(fieldOf(issue, 'code'), 'invalid'),
54
+ message: stringOr(fieldOf(issue, 'message'), ''),
55
+ };
56
+ });
57
+ };
58
+ const issuesOfDetails = (details) => {
59
+ const issues = details?.['issues'];
60
+ return Array.isArray(issues) ? issues.filter((issue) => typeof fieldOf(issue, 'path') === 'string') : [];
61
+ };
62
+ const traceOf = (error) => error instanceof Error && typeof error.stack === 'string' && error.stack.length > 0 ? error.stack.split('\n').map((line) => line.trimEnd()) : undefined;
63
+ const retryAfterOf = (error) => error instanceof RateLimitedError && error.retryAfterMs !== undefined ? { 'retry-after': String(Math.ceil(error.retryAfterMs / 1000)) } : {};
64
+ const classifyBuiltIn = (error, options) => {
65
+ if (error instanceof AppError) {
66
+ const status = (options.statusTable ?? DEFAULT_STATUS_TABLE).find(([type]) => error instanceof type)?.[1] ?? 500;
67
+ return { status, code: error.code, message: error.message, ...(error.details !== undefined ? { details: error.details } : {}), headers: retryAfterOf(error) };
68
+ }
69
+ const issues = fastifyIssuesOf(error) ?? zodIssuesOf(error);
70
+ if (issues !== null) {
71
+ return { status: 400, code: options.validationCode ?? 'REQUEST_INVALID', message: VALIDATION_MESSAGE, details: { issues } };
72
+ }
73
+ const frameworkCode = fieldOf(error, 'code');
74
+ const frameworkErrors = { ...DEFAULT_FRAMEWORK_ERRORS, ...options.frameworkErrors };
75
+ const known = typeof frameworkCode === 'string' && Object.hasOwn(frameworkErrors, frameworkCode) ? frameworkErrors[frameworkCode] : undefined;
76
+ if (known !== undefined)
77
+ return known;
78
+ const clientStatus = clientStatusOf(error);
79
+ if (clientStatus !== null) {
80
+ return { status: clientStatus, code: options.clientErrorCode ?? 'BAD_REQUEST', message: messageOf(error) };
81
+ }
82
+ return { status: 500, code: options.unknownCode ?? 'INTERNAL_ERROR' };
83
+ };
84
+ /**
85
+ * The one place an error becomes an HTTP status and a wire body `{ error: { id?, code, message, details?, trace? } }`.
86
+ * Framework-free: hand the result to your framework's error hook.
87
+ *
88
+ * - 4xx: the message and details go out, there is no id, and `log` is false.
89
+ * - 5xx: a generic message, no details, and an `id`; `log` is true so the hook logs the real error once with it.
90
+ * - Order: `classify`, then the status table for an `AppError`, then a request schema failure (400 with
91
+ * `details.issues`), then a known Fastify error code, then any framework 4xx `statusCode`, then 500.
92
+ */
93
+ export const mapError = (error, options = {}) => {
94
+ const classification = options.classify?.(error) ?? classifyBuiltIn(error, options);
95
+ const { status } = classification;
96
+ const server = status >= 500;
97
+ const trace = options.includeTrace === true ? traceOf(error) : undefined;
98
+ const details = server ? undefined : classification.details;
99
+ const wire = {
100
+ ...(server ? { id: (options.errorId ?? randomUUID)() } : {}),
101
+ code: classification.code,
102
+ message: server ? (options.internalMessage ?? 'Internal error') : (classification.message ?? messageOf(error)),
103
+ ...(details !== undefined ? { details } : {}),
104
+ ...(trace !== undefined ? { trace } : {}),
105
+ };
106
+ return { status, body: { error: wire }, log: server, headers: classification.headers ?? {}, issues: issuesOfDetails(details) };
107
+ };
@@ -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,45 @@
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.0",
4
+ "description": "Fastify error handler: maps @tcds-io/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
+ "@tcds-io/errors": "^0.1.0"
32
+ },
33
+ "engines": {
34
+ "node": ">=22"
35
+ },
36
+ "peerDependencies": {
37
+ "@tcds-io/errors": "~0.1.0",
38
+ "fastify": ">=5"
39
+ },
40
+ "scripts": {
41
+ "build": "tsc -p tsconfig.build.json",
42
+ "check:types": "tsc --noEmit -p .",
43
+ "test": "vitest run"
44
+ }
6
45
  }