@wthek/error-handling 0.0.0-stage → 1.0.0-beta.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.
Files changed (35) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +246 -2
  3. package/dist/bin.d.ts +36 -0
  4. package/dist/bin.d.ts.map +1 -0
  5. package/dist/bin.js +127 -0
  6. package/dist/index.d.ts +23 -0
  7. package/dist/index.d.ts.map +1 -0
  8. package/dist/index.js +67 -0
  9. package/dist/installer.d.ts +36 -0
  10. package/dist/installer.d.ts.map +1 -0
  11. package/dist/installer.js +139 -0
  12. package/dist/types.d.ts +25 -0
  13. package/dist/types.d.ts.map +1 -0
  14. package/dist/types.js +2 -0
  15. package/package.json +101 -3
  16. package/plugin.json +11 -0
  17. package/skills/wthek-error-handling/SKILL.md +711 -0
  18. package/skills/wthek-error-handling/examples/express-zod.js +44 -0
  19. package/skills/wthek-error-handling/examples/express-zod.ts +51 -0
  20. package/skills/wthek-error-handling/examples/fastify-zod.js +40 -0
  21. package/skills/wthek-error-handling/examples/fastify-zod.ts +45 -0
  22. package/skills/wthek-error-handling/examples/hono-valibot.ts +42 -0
  23. package/skills/wthek-error-handling/examples/koa-typebox.ts +54 -0
  24. package/skills/wthek-error-handling/references/express.md +73 -0
  25. package/skills/wthek-error-handling/references/fastify.md +81 -0
  26. package/skills/wthek-error-handling/references/formatters.md +241 -0
  27. package/skills/wthek-error-handling/references/hono.md +151 -0
  28. package/skills/wthek-error-handling/references/koa.md +62 -0
  29. package/skills/wthek-error-handling/references/mcp.md +148 -0
  30. package/skills/wthek-error-handling/references/nestjs.md +84 -0
  31. package/skills/wthek-error-handling/references/restify.md +68 -0
  32. package/skills/wthek-error-handling/references/status-codes.md +181 -0
  33. package/skills/wthek-error-handling/references/typebox.md +74 -0
  34. package/skills/wthek-error-handling/references/valibot.md +202 -0
  35. package/skills/wthek-error-handling/references/zod.md +113 -0
@@ -0,0 +1,711 @@
1
+ ---
2
+ name: wthek-error-handling
3
+ description: >-
4
+ Use this skill whenever adding, refactoring, configuring, or standardizing HTTP error handling, validation error pipelines (Zod, Valibot, TypeBox), HTTP status code usage, or MCP error formatting in Express, Fastify, Hono, Koa, NestJS, Restify, Node.js applications, or Model Context Protocol servers using @wthek packages, http-error-kit, and http-response-status-code.
5
+ ---
6
+
7
+ # WTHek Error Handling Skill
8
+
9
+ This skill guides the implementation of standardized, production-safe HTTP error handling and validation error pipelines using the `@wthek` ("What The HEK") extension suite powered by [`http-error-kit`](https://www.npmjs.com/package/http-error-kit) and [`http-response-status-code`](https://www.npmjs.com/package/http-response-status-code).
10
+
11
+ ---
12
+
13
+ ## 1. Package Decision Matrix
14
+
15
+ Inspect the project's `package.json` to identify the framework and validation libraries in use, then select the appropriate packages:
16
+
17
+ | Framework / Need | Primary Package | Companion Validation Package |
18
+ | :--- | :--- | :--- |
19
+ | **Express.js** | `@wthek/express-middleware` | `@wthek/zod-express-interceptor` (if Zod) · `@wthek/zod-transformer` · `@wthek/valibot-transformer` · `@wthek/typebox-transformer` |
20
+ | **Fastify** | `@wthek/fastify-middleware` | `@wthek/zod-transformer` · `@wthek/valibot-transformer` · `@wthek/typebox-transformer` |
21
+ | **Hono** | `@wthek/hono-middleware` | `@wthek/zod-transformer` · `@wthek/valibot-transformer` · `@wthek/typebox-transformer` |
22
+ | **Koa** | `@wthek/koa-middleware` | `@wthek/zod-transformer` · `@wthek/valibot-transformer` · `@wthek/typebox-transformer` |
23
+ | **NestJS** | `@wthek/nestjs-middleware` | `@wthek/zod-transformer` · `@wthek/valibot-transformer` · `@wthek/typebox-transformer` |
24
+ | **Restify** | `@wthek/restify-middleware` | `@wthek/zod-transformer` · `@wthek/valibot-transformer` · `@wthek/typebox-transformer` |
25
+ | **Framework-Agnostic / Utils** | `http-error-kit` | `@wthek/zod-transformer` · `@wthek/valibot-transformer` · `@wthek/typebox-transformer` |
26
+
27
+ ### Companion Packages (always install alongside)
28
+
29
+ | Package | Purpose |
30
+ | :--- | :--- |
31
+ | [`http-error-kit`](https://www.npmjs.com/package/http-error-kit) | Core error classes (`KitHttpError`, `KitGeneralError`, 42 named error classes) and formatter configuration (`KitHttpErrorConfig`) |
32
+ | [`http-response-status-code`](https://www.npmjs.com/package/http-response-status-code) | Type-safe, tree-shakeable HTTP status code constants and utilities |
33
+ | [`@wthek/mcp-error-formatter`](https://www.npmjs.com/package/@wthek/mcp-error-formatter) | Formats errors and `KitHttpError` instances into MCP tool results (`CallToolResult`), JSON-RPC 2.0 errors, and `KitHttpErrorConfig` formatters |
34
+ | [`@wthek/mcp`](https://www.npmjs.com/package/@wthek/mcp) | Standalone local MCP server providing AI agents with HTTP standards lookup, framework recipes, and code anti-pattern audits |
35
+
36
+ ---
37
+
38
+ ## 2. Core API: `http-error-kit`
39
+
40
+ ### Three Import Paths
41
+
42
+ | Import Path | Base Class | Formatter Support | Use Case |
43
+ | :--- | :--- | :--- | :--- |
44
+ | `http-error-kit` (default) | Dynamic — delegates to `KitHttpError` or `KitGeneralError` | Yes (when configured) | Standard usage |
45
+ | `http-error-kit/http` | Always `KitHttpError` | Yes (global + instance) | When you always want formatter support |
46
+ | `http-error-kit/generic` | Always `KitGeneralError` | No (static format) | Lightweight, no formatter needed |
47
+
48
+ ### KitHttpError Class
49
+
50
+ The primary error class. All `@wthek` middleware packages catch instances of this class (and `KitGeneralError`).
51
+
52
+ ```typescript
53
+ import { KitHttpError } from "http-error-kit";
54
+ import { NOT_FOUND, BAD_REQUEST } from "http-response-status-code";
55
+
56
+ // Basic usage
57
+ throw new KitHttpError(NOT_FOUND, "User not found");
58
+
59
+ // With details
60
+ throw new KitHttpError(BAD_REQUEST, "Invalid input", { field: "email" });
61
+
62
+ // With additional args (spread onto instance or passed to formatter)
63
+ throw new KitHttpError(BAD_REQUEST, "Validation failed", { issues: [...] }, { requestId: "abc" });
64
+ ```
65
+
66
+ #### Constructor
67
+
68
+ ```typescript
69
+ new KitHttpError(statusCode: number, message: string, details?: unknown, ...args: unknown[])
70
+ ```
71
+
72
+ #### Properties
73
+
74
+ | Property | Type | Description |
75
+ | :--- | :--- | :--- |
76
+ | `statusCode` | `number` | HTTP status code |
77
+ | `message` | `string` | Error message (inherited from `Error`) |
78
+ | `details` | `unknown` | Additional contextual information |
79
+ | `headers` | `Record<string, string> \| undefined` | HTTP response headers (e.g. WWW-Authenticate, Retry-After) |
80
+
81
+ #### Methods
82
+
83
+ | Method | Returns | Description |
84
+ | :--- | :--- | :--- |
85
+ | `getInputs()` | `IRawInput` | Returns `{ statusCode, message, details, args }` — original constructor arguments |
86
+ | `toJSON()` | `object` | Serializes using `instanceFormatter ?? defaultFormatter`, else `{ statusCode, message, details }` |
87
+ | `setFormatter(fn)` | `this` | Sets an instance-level formatter; returns `this` for chaining |
88
+ | `setHeader(name, value)` | `this` | Sets an individual response header; returns `this` for chaining |
89
+ | `setHeaders(headers)` | `this` | Sets multiple response headers; returns `this` for chaining |
90
+ | `toResponse(init?)` | `Response` | Converts error to a standard WHATWG Fetch `Response` (Next.js, Hono, Workers, Bun) |
91
+
92
+ ### Type Guards
93
+
94
+ ```typescript
95
+ import { isKitError, isKitHttpError, isKitGeneralError } from "http-error-kit";
96
+
97
+ try {
98
+ // ...
99
+ } catch (err: unknown) {
100
+ if (isKitError(err)) {
101
+ // Safe access to statusCode, toJSON(), toResponse(), headers
102
+ return err.toResponse();
103
+ }
104
+ }
105
+ ```
106
+
107
+ - **`isKitError(err)`**: True for any `KitHttpError`, `KitGeneralError`, or named error class
108
+ - **`isKitHttpError(err)`**: True for errors with configurable formatter support (`KitHttpError`)
109
+ - **`isKitGeneralError(err)`**: True for lightweight errors (`KitGeneralError`)
110
+
111
+ ### KitGeneralError Class
112
+
113
+ Lightweight alternative — same constructor as `KitHttpError` but without formatter support. Always serializes to `{ statusCode, message, details }`.
114
+
115
+ ### Named Error Classes (42 total)
116
+
117
+ `http-error-kit` exports pre-built error classes for every HTTP 4xx/5xx status code. Each class has the signature:
118
+
119
+ ```typescript
120
+ constructor(message?: string, details?: unknown, ...args: unknown[])
121
+ ```
122
+
123
+ The `message` defaults to the HTTP status description if omitted.
124
+
125
+ **4xx Client Errors:**
126
+ `BadRequestError` (400), `UnauthorizedError` (401), `PaymentRequiredError` (402), `ForbiddenError` (403), `NotFoundError` (404), `MethodNotAllowedError` (405), `NotAcceptableError` (406), `ProxyAuthenticationRequiredError` (407), `RequestTimeoutError` (408), `ConflictError` (409), `GoneError` (410), `LengthRequiredError` (411), `PreconditionFailedError` (412), `RequestTooLongError` (413), `RequestUriTooLongError` (414), `UnsupportedMediaTypeError` (415), `RequestedRangeNotSatisfiableError` (416), `ExpectationFailedError` (417), `ImATeapotError` (418), `InsufficientSpaceOnResourceError` (419), `MethodFailureError` (420), `MisdirectedRequestError` (421), `UnprocessableEntityError` (422), `LockedError` (423), `FailedDependencyError` (424), `TooEarlyError` (425), `UpgradeRequiredError` (426), `PreconditionRequiredError` (428), `TooManyRequestsError` (429), `RequestHeaderFieldsTooLargeError` (431), `UnavailableForLegalReasonsError` (451)
127
+
128
+ **5xx Server Errors:**
129
+ `InternalServerError` (500), `NotImplementedError` (501), `BadGatewayError` (502), `ServiceUnavailableError` (503), `GatewayTimeoutError` (504), `HttpVersionNotSupportedError` (505), `VariantAlsoNegotiatesError` (506), `InsufficientStorageError` (507), `LoopDetectedError` (508), `NotExtendedError` (510), `NetworkAuthenticationRequiredError` (511)
130
+
131
+ **Example usage:**
132
+
133
+ ```typescript
134
+ import { NotFoundError, BadRequestError } from "http-error-kit";
135
+
136
+ // No need to pass status code — it's built in
137
+ throw new NotFoundError("User not found");
138
+ throw new NotFoundError(); // defaults to "Not Found"
139
+ throw new BadRequestError("Invalid email", { field: "email" });
140
+ ```
141
+
142
+ ### Formatter Configuration (`KitHttpErrorConfig`)
143
+
144
+ Formatters control the shape of serialized error output (`toJSON()` / `res.send(error)`). The middleware packages call `res.send(error)` or `c.json(error.toJSON())`, so the formatter determines the response body shape.
145
+
146
+ ```typescript
147
+ import { KitHttpErrorConfig } from "http-error-kit";
148
+
149
+ // Configure once at server startup
150
+ KitHttpErrorConfig.configureFormatter((statusCode, message, details, ...args) => ({
151
+ type: `https://httpstatuses.com/${statusCode}`,
152
+ title: message,
153
+ status: statusCode,
154
+ detail: typeof details === "string" ? details : undefined,
155
+ invalidParams: typeof details === "object" ? details : undefined,
156
+ }));
157
+
158
+ // Reset to defaults
159
+ KitHttpErrorConfig.resetFormatter();
160
+ ```
161
+
162
+ **Instance-specific formatter** (overrides global):
163
+
164
+ ```typescript
165
+ const error = new KitHttpError(BAD_REQUEST, "Payment failed", { code: "CARD_DECLINED" });
166
+ error.setFormatter((statusCode, message, details) => ({
167
+ error_code: details?.code,
168
+ error_description: message,
169
+ }));
170
+ throw error; // .setFormatter() returns this, so chaining works too
171
+ ```
172
+
173
+ ### Types Reference
174
+
175
+ ```typescript
176
+ // Formatter function signature
177
+ type IFormatter = (statusCode: number, message: string, details: unknown, ...args: unknown[]) => unknown;
178
+
179
+ // Raw constructor inputs
180
+ interface IRawInput {
181
+ statusCode: number;
182
+ message: string;
183
+ details: unknown;
184
+ args: unknown[];
185
+ }
186
+ ```
187
+
188
+ ---
189
+
190
+ ## 3. HTTP Status Codes: `http-response-status-code`
191
+
192
+ ### Why Use It
193
+
194
+ - **Readability**: `NOT_FOUND` is self-documenting; `404` requires memorization
195
+ - **IDE discoverability**: Autocomplete surfaces all valid HTTP codes
196
+ - **Tree-shakeable**: Only imported codes are included in the bundle (`sideEffects: false`)
197
+ - **Zero dependencies**: Standalone, lightweight package
198
+ - **Utilities**: Helper functions for classification, description, and Fetch Response creation
199
+
200
+ ### Installation
201
+
202
+ ```bash
203
+ npm install http-response-status-code
204
+ ```
205
+
206
+ ### Import Patterns
207
+
208
+ ```typescript
209
+ // ESM — named imports (tree-shaking friendly)
210
+ import { OK, NOT_FOUND, INTERNAL_SERVER_ERROR } from "http-response-status-code";
211
+
212
+ // CJS
213
+ const { OK, NOT_FOUND } = require("http-response-status-code");
214
+
215
+ // Enum access (alternative)
216
+ import { CODES } from "http-response-status-code";
217
+ CODES.HTTP_CODE_404; // 404
218
+ ```
219
+
220
+ ### Naming Convention
221
+
222
+ Named constants use **`SCREAMING_SNAKE_CASE`** matching the HTTP status name: `NOT_FOUND`, `BAD_REQUEST`, `OK`, `INTERNAL_SERVER_ERROR`, etc.
223
+
224
+ The `CODES` enum uses the pattern **`HTTP_CODE_{number}`**: `CODES.HTTP_CODE_200`, `CODES.HTTP_CODE_404`, etc.
225
+
226
+ ### Complete Status Code Reference
227
+
228
+ #### 1xx Informational
229
+
230
+ | Constant | Code |
231
+ | :--- | :--- |
232
+ | `CONTINUE` | 100 |
233
+ | `SWITCHING_PROTOCOLS` | 101 |
234
+ | `PROCESSING` | 102 |
235
+ | `EARLY_HINTS` | 103 |
236
+ | `TOO_LONG` | 122 |
237
+
238
+ #### 2xx Success
239
+
240
+ | Constant | Code |
241
+ | :--- | :--- |
242
+ | `OK` | 200 |
243
+ | `CREATED` | 201 |
244
+ | `ACCEPTED` | 202 |
245
+ | `NON_AUTHORITATIVE_INFORMATION` | 203 |
246
+ | `NO_CONTENT` | 204 |
247
+ | `RESET_CONTENT` | 205 |
248
+ | `PARTIAL_CONTENT` | 206 |
249
+ | `MULTI_STATUS` | 207 |
250
+ | `ALREADY_REPORTED` | 208 |
251
+ | `IM_USED` | 226 |
252
+
253
+ #### 3xx Redirection
254
+
255
+ | Constant | Code |
256
+ | :--- | :--- |
257
+ | `MULTIPLE_CHOICES` | 300 |
258
+ | `MOVED_PERMANENTLY` | 301 |
259
+ | `MOVED_TEMPORARILY` | 302 |
260
+ | `SEE_OTHER` | 303 |
261
+ | `NOT_MODIFIED` | 304 |
262
+ | `USE_PROXY` | 305 |
263
+ | `SWITCH_PROXY` | 306 |
264
+ | `TEMPORARY_REDIRECT` | 307 |
265
+ | `PERMANENT_REDIRECT` | 308 |
266
+
267
+ #### 4xx Client Error
268
+
269
+ | Constant | Code |
270
+ | :--- | :--- |
271
+ | `BAD_REQUEST` | 400 |
272
+ | `UNAUTHORIZED` | 401 |
273
+ | `PAYMENT_REQUIRED` | 402 |
274
+ | `FORBIDDEN` | 403 |
275
+ | `NOT_FOUND` | 404 |
276
+ | `METHOD_NOT_ALLOWED` | 405 |
277
+ | `NOT_ACCEPTABLE` | 406 |
278
+ | `PROXY_AUTHENTICATION_REQUIRED` | 407 |
279
+ | `REQUEST_TIMEOUT` | 408 |
280
+ | `CONFLICT` | 409 |
281
+ | `GONE` | 410 |
282
+ | `LENGTH_REQUIRED` | 411 |
283
+ | `PRECONDITION_FAILED` | 412 |
284
+ | `REQUEST_TOO_LONG` | 413 |
285
+ | `REQUEST_URI_TOO_LONG` | 414 |
286
+ | `UNSUPPORTED_MEDIA_TYPE` | 415 |
287
+ | `REQUESTED_RANGE_NOT_SATISFIABLE` | 416 |
288
+ | `EXPECTATION_FAILED` | 417 |
289
+ | `IM_A_TEAPOT` | 418 |
290
+ | `INSUFFICIENT_SPACE_ON_RESOURCE` | 419 |
291
+ | `METHOD_FAILURE` | 420 |
292
+ | `MISDIRECTED_REQUEST` | 421 |
293
+ | `UNPROCESSABLE_ENTITY` | 422 |
294
+ | `LOCKED` | 423 |
295
+ | `FAILED_DEPENDENCY` | 424 |
296
+ | `TOO_EARLY` | 425 |
297
+ | `UPGRADE_REQUIRED` | 426 |
298
+ | `PRECONDITION_REQUIRED` | 428 |
299
+ | `TOO_MANY_REQUESTS` | 429 |
300
+ | `REQUEST_HEADER_FIELDS_TOO_LARGE` | 431 |
301
+ | `UNAVAILABLE_FOR_LEGAL_REASONS` | 451 |
302
+
303
+ #### 5xx Server Error
304
+
305
+ | Constant | Code |
306
+ | :--- | :--- |
307
+ | `INTERNAL_SERVER_ERROR` | 500 |
308
+ | `NOT_IMPLEMENTED` | 501 |
309
+ | `BAD_GATEWAY` | 502 |
310
+ | `SERVICE_UNAVAILABLE` | 503 |
311
+ | `GATEWAY_TIMEOUT` | 504 |
312
+ | `HTTP_VERSION_NOT_SUPPORTED` | 505 |
313
+ | `VARIANT_ALSO_NEGOTIATES` | 506 |
314
+ | `INSUFFICIENT_STORAGE` | 507 |
315
+ | `LOOP_DETECTED` | 508 |
316
+ | `NOT_EXTENDED` | 510 |
317
+ | `NETWORK_AUTHENTICATION_REQUIRED` | 511 |
318
+
319
+ ### Utility Functions
320
+
321
+ | Function | Signature | Description |
322
+ | :--- | :--- | :--- |
323
+ | `getStatusCode(name)` | `(name: string) => number` | Get code from name: `getStatusCode("NOT_FOUND")` → `404` |
324
+ | `getStatusName(code)` | `(code: number) => string` | Get name from code: `getStatusName(404)` → `"NOT_FOUND"` |
325
+ | `getStatusDescription(code)` | `(code: number) => string` | Human-readable: `getStatusDescription(500)` → `"Internal Server Error"` |
326
+ | `toResponseInit(code, init?)` | `<T>(code: number \| string, init?: T) => IResponseInit & T` | Fetch API helper: `new Response(body, toResponseInit(OK))` |
327
+ | `isInformational(code)` | `(code: number) => boolean` | `true` if 1xx (throws for invalid codes) |
328
+ | `isSuccess(code)` | `(code: number) => boolean` | `true` if 2xx (throws for invalid codes) |
329
+ | `isRedirectional(code)` | `(code: number) => boolean` | `true` if 3xx (throws for invalid codes) |
330
+ | `isClientError(code)` | `(code: number) => boolean` | `true` if 4xx (throws for invalid codes) |
331
+ | `isServerError(code)` | `(code: number) => boolean` | `true` if 5xx (throws for invalid codes) |
332
+ | `isValidStatusCode(code)` | `(code: number) => boolean` | Safe check — returns `false` instead of throwing for invalid codes |
333
+ | `getInformationalCodes()` | `() => number[]` | All 1xx codes |
334
+ | `getSuccessCodes()` | `() => number[]` | All 2xx codes |
335
+ | `getRedirectionalCodes()` | `() => number[]` | All 3xx codes |
336
+ | `getClientErrorCodes()` | `() => number[]` | All 4xx codes |
337
+ | `getServerErrorCodes()` | `() => number[]` | All 5xx codes |
338
+
339
+ > **Warning:** All `is*` validators (except `isValidStatusCode`) **throw an Error** for unrecognized status codes. Use `isValidStatusCode(code)` first if you need a safe check.
340
+
341
+ ### Integration with http-error-kit
342
+
343
+ **Always prefer named constants over magic numbers** when constructing errors:
344
+
345
+ ```typescript
346
+ import { KitHttpError } from "http-error-kit";
347
+ import { NOT_FOUND, BAD_REQUEST } from "http-response-status-code";
348
+
349
+ // ❌ AVOID: Magic numbers
350
+ throw new KitHttpError(404, "User not found");
351
+
352
+ // ✅ PREFERRED: Named constants
353
+ throw new KitHttpError(NOT_FOUND, "User not found");
354
+ ```
355
+
356
+ #### With Named Error Classes
357
+
358
+ ```typescript
359
+ // Named error classes already have the status code baked in,
360
+ // so http-response-status-code is used for other purposes:
361
+ import { NotFoundError } from "http-error-kit";
362
+ import { CREATED, NO_CONTENT } from "http-response-status-code";
363
+
364
+ throw new NotFoundError("User not found"); // 404 is automatic
365
+
366
+ // For success responses:
367
+ res.status(CREATED).json({ user });
368
+ res.status(NO_CONTENT).send();
369
+ ```
370
+
371
+ #### With Validation Transformers
372
+
373
+ ```typescript
374
+ import { KitZodTransformer } from "@wthek/zod-transformer";
375
+ import { UNPROCESSABLE_ENTITY } from "http-response-status-code";
376
+
377
+ try {
378
+ schema.parse(data);
379
+ } catch (error) {
380
+ KitZodTransformer(error, { statusCode: UNPROCESSABLE_ENTITY });
381
+ }
382
+ ```
383
+
384
+ #### With Fetch API / Web Standards
385
+
386
+ ```typescript
387
+ import { toResponseInit, OK, NOT_FOUND } from "http-response-status-code";
388
+
389
+ // Hono, Next.js App Router, Cloudflare Workers, Deno, Bun
390
+ return Response.json({ data }, toResponseInit(OK));
391
+ return Response.json({ error: "Not found" }, toResponseInit(NOT_FOUND));
392
+
393
+ // With extra init options
394
+ return new Response(body, toResponseInit(OK, {
395
+ headers: { "Content-Type": "application/json" },
396
+ }));
397
+ ```
398
+
399
+ ---
400
+
401
+ ## 4. Mandatory Architectural Guardrails
402
+
403
+ When writing or refactoring error handling code with `@wthek`, you **must** enforce these rules:
404
+
405
+ ### A. Framework Error Registration Patterns
406
+
407
+ Each framework registers the error handler differently. **Get this right first.**
408
+
409
+ | Framework | How to Register | Pattern |
410
+ | :--- | :--- | :--- |
411
+ | **Express** | `app.use(KitExpressMiddleware())` | Terminal error middleware (last `app.use`) |
412
+ | **Fastify** | `KitFastifyMiddleware(app, opts)` or `app.setErrorHandler(KitFastifyErrorHandler(opts))` | Error handler hook |
413
+ | **Hono** | `KitHonoMiddleware(app, opts)` or `app.onError(KitHonoErrorHandler(opts))` | `app.onError()` handler |
414
+ | **Koa** | `KitKoaMiddleware(app, opts)` or `app.use(KitKoaMiddleware(opts))` | Onion middleware (register at **top** of stack) |
415
+ | **NestJS** | `app.useGlobalFilters(new KitExceptionFilter(opts))` | Exception filter |
416
+ | **Restify** | `server.on("restifyError", KitRestifyMiddleware(opts))` | Error event listener |
417
+
418
+ ### B. Middleware Execution Pipeline Ordering
419
+
420
+ - **Express** — Error middleware must be the **last** `app.use()`. Interceptors go after routes but before the error middleware.
421
+ - **Koa** — Error middleware must be at the **top** of the middleware stack (opposite of Express) because Koa uses an onion architecture where upstream middleware wraps downstream in `try/catch`.
422
+
423
+ ```typescript
424
+ // ❌ WRONG (Express): Interceptor placed before routes
425
+ app.use(KitZodExpressInterceptor());
426
+ app.post("/users", userHandler);
427
+
428
+ // ✅ CORRECT (Express): Routes → Interceptors → Final Error Middleware
429
+ app.post("/users", userHandler);
430
+ app.use(KitZodExpressInterceptor());
431
+ app.use(KitExpressMiddleware());
432
+
433
+ // ✅ CORRECT (Koa): Error middleware at the TOP
434
+ app.use(KitKoaMiddleware({ handleUnknownErrors: true }));
435
+ app.use(router.routes());
436
+ ```
437
+
438
+ ### C. Streaming & Headers Sent Protection
439
+
440
+ - In Express / Restify: `if (res.headersSent) { next(error); return; }`
441
+ - In Fastify: `if (reply.sent) { return; }`
442
+ - In Koa: `if (ctx.headerSent) { return; }`
443
+
444
+ > **Note:** The `@wthek/express-middleware` and `@wthek/koa-middleware` have **built-in headers-sent checks**. This guardrail applies to **custom error handlers** you write manually.
445
+
446
+ ### D. Type Safety Standards
447
+
448
+ - Never annotate caught errors as `error: any`. Always use `error: unknown`.
449
+ - Use nullish coalescing `??` instead of logical OR `||` when reading status codes (e.g., `statusCode ?? 400`).
450
+ - **Use `http-response-status-code` constants** instead of magic numbers for all status codes.
451
+
452
+ ### E. Redundant Try/Catch Elimination
453
+
454
+ - Do not wrap code in `try { ... } catch (err) { throw err; }`. Only catch if handling, transforming, or logging.
455
+
456
+ ### F. How Middlewares Serialize Errors
457
+
458
+ All `@wthek` middleware packages serialize errors through `error.toJSON()` (via `res.send(error)` in Express, or `c.json(error.toJSON())` in Hono). This means:
459
+
460
+ 1. The **response body shape** is controlled by the formatter configured via `KitHttpErrorConfig.configureFormatter()` or `error.setFormatter()` — NOT by middleware options.
461
+ 2. Middleware options control **logging** and **unknown error handling** only.
462
+ 3. Without a formatter, the default output is: `{ statusCode, message, details }`.
463
+
464
+ ---
465
+
466
+ ## 5. Middleware Options Reference
467
+
468
+ All `@wthek` middleware packages have consistent options:
469
+
470
+ | Option | Type | Default | Description |
471
+ | :--- | :--- | :--- | :--- |
472
+ | `log` | `boolean \| ((error: unknown, req/c/ctx) => void)` | `false` | When `true`, logs via `console.error` (Fastify uses `request.log.error`). When a function, invokes custom logging. |
473
+ | `handleUnknownErrors` | `boolean` | `false` | If `true`, non-Kit errors return a structured `{ statusCode: 500, message: "Internal Server Error" }` JSON response instead of framework defaults. |
474
+
475
+ #### Koa-Specific Extra Option
476
+
477
+ | Option | Type | Default | Description |
478
+ | :--- | :--- | :--- | :--- |
479
+ | `emitAppError` | `boolean` | `false` | When `true`, calls `ctx.app.emit("error", error, ctx)` to notify centralized app listeners (e.g., Sentry, Datadog). |
480
+
481
+ ### Fastify, Hono & Koa: Two Setup Approaches
482
+
483
+ Both Fastify, Hono, and Koa middleware packages export two setup approaches:
484
+
485
+ | Function | Description |
486
+ | :--- | :--- |
487
+ | `KitFastifyMiddleware(app, opts)` / `KitHonoMiddleware(app, opts)` / `KitKoaMiddleware(app, opts)` | Convenience wrapper — registers the handler globally on the app instance |
488
+ | `KitFastifyErrorHandler(opts)` / `KitHonoErrorHandler(opts)` / `app.use(KitKoaMiddleware(opts))` | Returns a handler/middleware for manual registration (scoped plugins, sub-routers) |
489
+
490
+ ### Transformer Options
491
+
492
+ Available on: `IKitZodTransformerOptions`, `IKitZodExpressInterceptorOptions` (same type), `IKitValibotTransformerOptions`, `IKitTypeBoxTransformerOptions`
493
+
494
+ | Option | Type | Default | Description |
495
+ | :--- | :--- | :--- | :--- |
496
+ | `message` | `string` | `"Zod Validation Failed"` / `"Valibot Validation Failed"` / `"TypeBox Validation Failed"` | Custom error message for the validation failure. |
497
+ | `statusCode` | `number` | `400` (`BAD_REQUEST`) | Custom HTTP status code. Use `UNPROCESSABLE_ENTITY` from `http-response-status-code` for semantic correctness. |
498
+
499
+ ---
500
+
501
+ ## 6. Validation Library Integration
502
+
503
+ ### Zod
504
+
505
+ Two packages are available:
506
+
507
+ | Package | Type | Use Case |
508
+ | :--- | :--- | :--- |
509
+ | `@wthek/zod-express-interceptor` | Express error middleware | Automatic — sits in the Express error pipeline, converts `ZodError` via `next()` |
510
+ | `@wthek/zod-transformer` | Pure functions | Manual — call in catch blocks for Fastify, Hono, NestJS, Restify, or any framework |
511
+
512
+ #### `@wthek/zod-transformer` exports two functions:
513
+
514
+ | Function | Returns | Behavior |
515
+ | :--- | :--- | :--- |
516
+ | `fromZodError(error, opts?)` | `KitHttpError \| null` | **Non-throwing.** Returns `KitHttpError` if input is `ZodError`, else `null`. |
517
+ | `KitZodTransformer(error, opts?)` | `never` | **Always throws.** Throws `KitHttpError` if `ZodError`, otherwise re-throws the original error unchanged. |
518
+
519
+ #### Error Payload Structure (Zod)
520
+
521
+ Zod issues are preserved in `error.details.issues`:
522
+
523
+ ```json
524
+ {
525
+ "statusCode": 400,
526
+ "message": "Zod Validation Failed",
527
+ "details": {
528
+ "issues": [
529
+ { "code": "too_small", "minimum": 18, "type": "number", "message": "...", "path": ["age"] }
530
+ ]
531
+ }
532
+ }
533
+ ```
534
+
535
+ ### Valibot
536
+
537
+ | Package | Type | Use Case |
538
+ | :--- | :--- | :--- |
539
+ | `@wthek/valibot-transformer` | Pure functions | Manual — call in catch blocks for any framework |
540
+
541
+ **Peer dependencies:** `valibot >= 1.0.0`, `http-error-kit >= 1.2.0`
542
+
543
+ #### `@wthek/valibot-transformer` exports two functions:
544
+
545
+ | Function | Returns | Behavior |
546
+ | :--- | :--- | :--- |
547
+ | `fromValiError(error, opts?)` | `KitHttpError \| null` | **Non-throwing.** Returns `KitHttpError` if input is `ValiError`, else `null`. |
548
+ | `KitValibotTransformer(error, opts?)` | `never` | **Always throws.** Throws `KitHttpError` if `ValiError`, otherwise re-throws unchanged. |
549
+
550
+ ```typescript
551
+ import { KitValibotTransformer } from "@wthek/valibot-transformer";
552
+ import * as v from "valibot";
553
+ import { UNPROCESSABLE_ENTITY } from "http-response-status-code";
554
+
555
+ const schema = v.object({
556
+ name: v.string(),
557
+ age: v.pipe(v.number(), v.minValue(18)),
558
+ });
559
+
560
+ try {
561
+ v.parse(schema, data);
562
+ } catch (err) {
563
+ KitValibotTransformer(err, {
564
+ message: "Validation Failed",
565
+ statusCode: UNPROCESSABLE_ENTITY,
566
+ });
567
+ }
568
+ ```
569
+
570
+ #### Error Payload Structure (Valibot)
571
+
572
+ Valibot issues are preserved in `error.details.issues`:
573
+
574
+ ```json
575
+ {
576
+ "statusCode": 400,
577
+ "message": "Valibot Validation Failed",
578
+ "details": {
579
+ "issues": [
580
+ { "kind": "validation", "type": "min_value", "message": "...", "path": [...] }
581
+ ]
582
+ }
583
+ }
584
+ ```
585
+
586
+ ### TypeBox
587
+
588
+ | Package | Type | Use Case |
589
+ | :--- | :--- | :--- |
590
+ | `@wthek/typebox-transformer` | Pure functions | Manual — call in catch blocks for any framework |
591
+
592
+ **Peer dependencies:** `@sinclair/typebox >= 0.32.0`, `http-error-kit >= 1.2.0`
593
+
594
+ #### `@wthek/typebox-transformer` exports two functions:
595
+
596
+ | Function | Returns | Behavior |
597
+ | :--- | :--- | :--- |
598
+ | `fromTypeBoxError(error, opts?)` | `KitHttpError \| null` | **Non-throwing.** Returns `KitHttpError` if input is a TypeBox error, else `null`. |
599
+ | `KitTypeBoxTransformer(error, opts?)` | `never` | **Always throws.** Throws `KitHttpError` if TypeBox error, otherwise re-throws unchanged. |
600
+
601
+ #### Supported TypeBox Error Input Formats
602
+
603
+ Unlike Zod/Valibot which have a single error type, TypeBox has multiple error representations. The transformer handles **all** of them:
604
+
605
+ - `TypeBoxError` instances (including `AssertError` from `Value.Assert()`)
606
+ - `ValueError[]` arrays (e.g., `[...Value.Errors(schema, data)]`)
607
+ - `ValueErrorIterator` iterators directly (e.g., `Value.Errors(schema, data)`)
608
+ - Single `ValueError` objects
609
+ - Objects with an `.errors` property containing `ValueError[]`
610
+
611
+ ```typescript
612
+ import { Type } from "@sinclair/typebox";
613
+ import { Value } from "@sinclair/typebox/value";
614
+ import { KitTypeBoxTransformer } from "@wthek/typebox-transformer";
615
+ import { UNPROCESSABLE_ENTITY } from "http-response-status-code";
616
+
617
+ const UserSchema = Type.Object({
618
+ name: Type.String(),
619
+ age: Type.Number({ minimum: 18 }),
620
+ });
621
+
622
+ // Pattern 1: With Value.Assert (throws TypeBoxError)
623
+ try {
624
+ Value.Assert(UserSchema, data);
625
+ } catch (err) {
626
+ KitTypeBoxTransformer(err, { statusCode: UNPROCESSABLE_ENTITY });
627
+ }
628
+
629
+ // Pattern 2: With Value.Errors (returns iterator)
630
+ import { fromTypeBoxError } from "@wthek/typebox-transformer";
631
+ const errors = [...Value.Errors(UserSchema, data)];
632
+ const kitError = fromTypeBoxError(errors);
633
+ if (kitError) throw kitError;
634
+ ```
635
+
636
+ #### Error Payload Structure (TypeBox)
637
+
638
+ TypeBox issues are preserved in `error.details.issues`:
639
+
640
+ ```json
641
+ {
642
+ "statusCode": 400,
643
+ "message": "TypeBox Validation Failed",
644
+ "details": {
645
+ "issues": [
646
+ { "type": 38, "path": "/age", "value": 14, "message": "Expected number to be greater or equal to 18" }
647
+ ]
648
+ }
649
+ }
650
+ ```
651
+
652
+ ---
653
+
654
+ ## 7. Progressive Guides & Recipes
655
+
656
+ Read the dedicated reference guide for your specific framework:
657
+
658
+ - [Express.js Implementation Guide](./references/express.md)
659
+ - [Fastify Implementation Guide](./references/fastify.md)
660
+ - [Hono Implementation Guide](./references/hono.md)
661
+ - [Koa Implementation Guide](./references/koa.md)
662
+ - [NestJS Implementation Guide](./references/nestjs.md)
663
+ - [Restify Implementation Guide](./references/restify.md)
664
+ - [Zod Validation Integration Guide](./references/zod.md)
665
+ - [Valibot Validation Integration Guide](./references/valibot.md)
666
+ - [TypeBox Validation Integration Guide](./references/typebox.md)
667
+ - [Custom Formatters, RFC-7807 & RFC-9457 Guide](./references/formatters.md)
668
+ - [http-response-status-code Usage Guide](./references/status-codes.md)
669
+ - [MCP & AI Agent Integration Guide](./references/mcp.md)
670
+
671
+ ---
672
+
673
+ ## 8. Default JSON Response Format
674
+
675
+ Without a custom formatter, all `@wthek` middlewares produce this structure (via `error.toJSON()`):
676
+
677
+ ```json
678
+ {
679
+ "statusCode": 400,
680
+ "message": "Error description",
681
+ "details": null
682
+ }
683
+ ```
684
+
685
+ For unknown errors (when `handleUnknownErrors: true`):
686
+
687
+ ```json
688
+ {
689
+ "statusCode": 500,
690
+ "message": "Internal Server Error"
691
+ }
692
+ ```
693
+
694
+ With a formatter configured via `KitHttpErrorConfig.configureFormatter()`, the output shape is entirely controlled by your formatter function.
695
+
696
+ ---
697
+
698
+ ## 9. Verification Checklist
699
+
700
+ Before finalizing any error-handling task:
701
+
702
+ 1. ✅ Verify error handler is registered correctly for the framework (see Section 4A).
703
+ 2. ✅ Verify interceptors are registered **after** route definitions (Express only).
704
+ 3. ✅ Test a synthetic 400 error (e.g., invalid Zod/Valibot schema payload) to confirm structured JSON output.
705
+ 4. ✅ Test a synthetic 500 unhandled runtime error to confirm fallback behavior.
706
+ 5. ✅ Ensure `http-response-status-code` constants are used instead of magic numbers.
707
+ 6. ✅ Ensure `error: unknown` typing (never `error: any`).
708
+ 7. ✅ Ensure nullish coalescing `??` for status code fallbacks (not `||`).
709
+ 8. ✅ Verify no redundant `try/catch` blocks that only re-throw.
710
+ 9. ✅ Confirm formatter configuration (if any) is set once at startup via `KitHttpErrorConfig.configureFormatter()`.
711
+ 10. ✅ Ensure 100% test coverage if writing tests for custom adapters.