@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,151 @@
1
+ # Hono Error Handling with @wthek
2
+
3
+ Guide for implementing `@wthek/hono-middleware`.
4
+
5
+ ---
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ npm install @wthek/hono-middleware http-error-kit http-response-status-code
11
+ ```
12
+
13
+ **Peer dependency:** `hono >= 4.0.0`
14
+ **Multi-runtime:** Node.js, Cloudflare Workers, Deno, Bun
15
+
16
+ ---
17
+
18
+ ## 1. Global Setup (`KitHonoMiddleware`)
19
+
20
+ Attaches the error handler across the entire Hono application instance via `app.onError`:
21
+
22
+ ```typescript
23
+ import { Hono } from "hono";
24
+ import { KitHonoMiddleware } from "@wthek/hono-middleware";
25
+ import { KitHttpError } from "http-error-kit";
26
+ import { NOT_FOUND } from "http-response-status-code";
27
+
28
+ const app = new Hono();
29
+
30
+ app.get("/users/:id", (c) => {
31
+ throw new KitHttpError(NOT_FOUND, "User Not Found", { id: c.req.param("id") });
32
+ });
33
+
34
+ // Attach global error handler
35
+ KitHonoMiddleware(app, {
36
+ log: true,
37
+ handleUnknownErrors: true,
38
+ });
39
+
40
+ export default app;
41
+ ```
42
+
43
+ ---
44
+
45
+ ## 2. Standalone Error Handler (`KitHonoErrorHandler`)
46
+
47
+ Returns a Hono-compatible `ErrorHandler` function for `app.onError()` or sub-routers:
48
+
49
+ ```typescript
50
+ import { Hono } from "hono";
51
+ import { KitHonoErrorHandler } from "@wthek/hono-middleware";
52
+
53
+ const app = new Hono();
54
+
55
+ app.onError(
56
+ KitHonoErrorHandler({
57
+ log: (err, c) => console.error(`Error on ${c.req.method} ${c.req.path}:`, err),
58
+ handleUnknownErrors: true,
59
+ })
60
+ );
61
+ ```
62
+
63
+ ---
64
+
65
+ ## With Zod Validation
66
+
67
+ ```typescript
68
+ import { fromZodError } from "@wthek/zod-transformer";
69
+ import { z } from "zod";
70
+ import { UNPROCESSABLE_ENTITY } from "http-response-status-code";
71
+
72
+ app.post("/users", async (c) => {
73
+ const body = await c.req.json();
74
+ try {
75
+ const user = UserSchema.parse(body);
76
+ return c.json({ success: true, data: user }, 201);
77
+ } catch (error) {
78
+ const kitError = fromZodError(error, { statusCode: UNPROCESSABLE_ENTITY });
79
+ if (kitError) throw kitError;
80
+ throw error;
81
+ }
82
+ });
83
+ ```
84
+
85
+ ## With Valibot Validation
86
+
87
+ ```typescript
88
+ import { KitValibotTransformer } from "@wthek/valibot-transformer";
89
+ import * as v from "valibot";
90
+ import { UNPROCESSABLE_ENTITY } from "http-response-status-code";
91
+
92
+ app.post("/users", async (c) => {
93
+ const body = await c.req.json();
94
+ try {
95
+ const user = v.parse(UserSchema, body);
96
+ return c.json(user, 201);
97
+ } catch (error) {
98
+ KitValibotTransformer(error, { statusCode: UNPROCESSABLE_ENTITY });
99
+ }
100
+ });
101
+ ```
102
+
103
+ ## With TypeBox Validation
104
+
105
+ ```typescript
106
+ import { KitTypeBoxTransformer } from "@wthek/typebox-transformer";
107
+ import { Value } from "@sinclair/typebox/value";
108
+ import { Type } from "@sinclair/typebox";
109
+
110
+ const UserSchema = Type.Object({ name: Type.String(), age: Type.Number({ minimum: 18 }) });
111
+
112
+ app.post("/users", async (c) => {
113
+ const body = await c.req.json();
114
+ try {
115
+ Value.Assert(UserSchema, body);
116
+ return c.json(body, 201);
117
+ } catch (error) {
118
+ KitTypeBoxTransformer(error);
119
+ }
120
+ });
121
+ ```
122
+
123
+ ---
124
+
125
+ ## Options Reference
126
+
127
+ ```typescript
128
+ interface IKitHonoMiddlewareOptions {
129
+ // When true, logs via console.error.
130
+ // When a callback is provided, receives (error: unknown, c: Context).
131
+ log?: boolean | ((error: unknown, c: Context) => void);
132
+
133
+ // When true, catches any uncaught non-KitHttpError and formats as a 500 response.
134
+ handleUnknownErrors?: boolean;
135
+ }
136
+ ```
137
+
138
+ ---
139
+
140
+ ## Error Handling Behavior
141
+
142
+ 1. **KitHttpError / KitGeneralError**: Extracts `statusCode` via `error.getInputs()`, serializes via `error.toJSON()`, returns `c.json(payload, statusCode)`.
143
+ 2. **Unknown errors + `handleUnknownErrors: true`**: Returns `c.json({ statusCode: 500, message: "Internal Server Error" }, 500)`.
144
+ 3. **Unknown errors + `handleUnknownErrors: false`**: Returns `c.text(error.message, 500)`.
145
+ 4. **Internal failure**: Returns `c.text("Internal Server Error", 500)` as ultimate fallback.
146
+
147
+ ## Key Differences from Other Frameworks
148
+
149
+ - Uses `app.onError()` handler (not middleware chain or event)
150
+ - No Express-style pipeline ordering — error handler is a single registered function
151
+ - Uses `KitZodTransformer` / `KitValibotTransformer` / `KitTypeBoxTransformer` (manual), not interceptors
@@ -0,0 +1,62 @@
1
+ # Koa Error Handling with @wthek
2
+
3
+ Guide for implementing `@wthek/koa-middleware`.
4
+
5
+ ---
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ npm install @wthek/koa-middleware http-error-kit http-response-status-code
11
+ ```
12
+
13
+ ---
14
+
15
+ ## 1. Global Setup (`KitKoaMiddleware`)
16
+
17
+ In Koa's onion middleware architecture, error middleware sits at or near the **very top** of the middleware stack so that it wraps all downstream execution in `try ... catch`:
18
+
19
+ ```typescript
20
+ import Koa from "koa";
21
+ import { KitKoaMiddleware } from "@wthek/koa-middleware";
22
+ import { KitHttpError } from "http-error-kit";
23
+ import { NOT_FOUND } from "http-response-status-code";
24
+
25
+ const app = new Koa();
26
+
27
+ // Register at the top of middleware stack
28
+ app.use(
29
+ KitKoaMiddleware({
30
+ log: true,
31
+ handleUnknownErrors: true,
32
+ emitAppError: true,
33
+ }),
34
+ );
35
+
36
+ // Downstream routes / middleware
37
+ app.use(async (ctx) => {
38
+ if (ctx.path === "/users/me") {
39
+ throw new KitHttpError(NOT_FOUND, "User Not Found", { id: "me" });
40
+ }
41
+ ctx.body = { ok: true };
42
+ });
43
+
44
+ export default app;
45
+ ```
46
+
47
+ ---
48
+
49
+ ## 2. Configuration Options
50
+
51
+ | Option | Type | Default | Description |
52
+ | :--- | :--- | :--- | :--- |
53
+ | `log` | `boolean \| ((error: unknown, ctx: Context) => void)` | `false` | When `true`, logs via `console.error`. When a function is provided, receives `(error, ctx)` for custom logging. |
54
+ | `handleUnknownErrors` | `boolean` | `false` | When `true`, unhandled non-Kit errors return a structured 500 JSON response instead of re-throwing. |
55
+ | `emitAppError` | `boolean` | `false` | When `true`, calls `ctx.app.emit("error", error, ctx)` to notify centralized app listeners (e.g. Sentry). |
56
+
57
+ ---
58
+
59
+ ## 3. Streaming and Headers Sent Guard
60
+
61
+ If headers have already been sent to the client (e.g., long-lived streams or partial responses), `KitKoaMiddleware` skips writing status or body to prevent ERR_HTTP_HEADERS_SENT exceptions.
62
+
@@ -0,0 +1,148 @@
1
+ # Model Context Protocol (MCP) & AI Agent Integration
2
+
3
+ This reference covers the `@wthek` extensions designed for AI coding agents and MCP server architectures:
4
+ 1. [`@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, or centralized formatter payloads.
5
+ 2. [`@wthek/mcp`](https://www.npmjs.com/package/@wthek/mcp) – Standalone local MCP server providing AI agents with HTTP standards lookup, framework recipes, and error-handling code audits.
6
+
7
+ ---
8
+
9
+ ## 1. `@wthek/mcp-error-formatter`
10
+
11
+ ### Purpose & Architecture
12
+
13
+ In Model Context Protocol (MCP) tool handlers, throwing raw errors or returning unstructured text strings degrades AI agent performance. `@wthek/mcp-error-formatter` bridges the `@wthek` error ecosystem into standard MCP tool results (`CallToolResult`), JSON-RPC 2.0 error responses, and `KitHttpErrorConfig` pipelines.
14
+
15
+ ```
16
+ Application / MCP Tool Handler
17
+ │
18
+ (Error Thrown / Caught)
19
+ │
20
+ ▼
21
+ ┌───────────────────────────────┐
22
+ │ @wthek/mcp-error-formatter │
23
+ └──────────────┬────────────────┘
24
+ │
25
+ ┌────────────────┼────────────────┐
26
+ ▼ ▼ ▼
27
+ toMcpToolResult() toMcpProtocolError() mcpErrorFormatter()
28
+ │ │ │
29
+ ▼ ▼ ▼
30
+ MCP CallToolResult JSON-RPC 2.0 Error http-error-kit Formatter
31
+ (isError: true) (code, message) (KitHttpErrorConfig)
32
+ │ │ │
33
+ └────────────────┼────────────────┘
34
+ │
35
+ ▼
36
+ MCP Client / AI Agent
37
+ ```
38
+
39
+ ### Installation
40
+
41
+ ```bash
42
+ npm install @wthek/mcp-error-formatter http-error-kit http-response-status-code
43
+ ```
44
+
45
+ ### Key Functions
46
+
47
+ #### A. `toMcpToolResult(error, options?)`
48
+ Transforms any error into a standard MCP `CallToolResult` with `isError: true`, formatted text content, and structured `_meta.error` metadata.
49
+
50
+ ```typescript
51
+ import { NotFoundError } from "http-error-kit";
52
+ import { toMcpToolResult } from "@wthek/mcp-error-formatter";
53
+
54
+ try {
55
+ throw new NotFoundError("User not found", { userId: 42 });
56
+ } catch (error: unknown) {
57
+ const result = toMcpToolResult(error, {
58
+ includeMeta: true,
59
+ recoveryHint: "Verify the user ID before retrying.",
60
+ });
61
+ return result;
62
+ }
63
+ ```
64
+
65
+ Result output:
66
+ ```json
67
+ {
68
+ "isError": true,
69
+ "content": [
70
+ {
71
+ "type": "text",
72
+ "text": "[HTTP 404] User not found\nDetails: {\n \"userId\": 42\n}"
73
+ }
74
+ ],
75
+ "_meta": {
76
+ "error": {
77
+ "category": "RESOURCE",
78
+ "code": -32004,
79
+ "recoveryHint": "Verify the user ID before retrying.",
80
+ "retryable": false
81
+ }
82
+ }
83
+ }
84
+ ```
85
+
86
+ #### B. `toMcpProtocolError(error)`
87
+ Transforms an error into a standard JSON-RPC 2.0 protocol error object:
88
+
89
+ ```typescript
90
+ import { toMcpProtocolError } from "@wthek/mcp-error-formatter";
91
+
92
+ const rpcError = toMcpProtocolError(new Error("Database connection timed out"));
93
+ // { code: -32603, message: "Database connection timed out" }
94
+ ```
95
+
96
+ #### C. `mcpErrorFormatter(statusCode, message, details?)`
97
+ Plugs into `KitHttpErrorConfig.configureFormatter()` to format all `KitHttpError.toJSON()` calls into MCP-compliant payloads:
98
+
99
+ ```typescript
100
+ import { KitHttpErrorConfig, NotFoundError } from "http-error-kit";
101
+ import { mcpErrorFormatter } from "@wthek/mcp-error-formatter";
102
+
103
+ // Configure once at application startup
104
+ KitHttpErrorConfig.configureFormatter(mcpErrorFormatter);
105
+
106
+ const error = new NotFoundError("Document not found");
107
+ console.log(error.toJSON());
108
+ ```
109
+
110
+ ---
111
+
112
+ ## 2. `@wthek/mcp` (Local Agent MCP Server)
113
+
114
+ ### Purpose
115
+
116
+ `@wthek/mcp` is a local MCP server that gives AI coding agents (Claude Desktop, Cursor, Antigravity) deterministic tools to inspect HTTP standards, generate copy-paste framework setup recipes, and audit source code for error anti-patterns.
117
+
118
+ ### Agent Configuration
119
+
120
+ Install the package first, then configure the MCP server:
121
+
122
+ ```bash
123
+ npm install @wthek/mcp
124
+ ```
125
+
126
+ ```json
127
+ {
128
+ "mcpServers": {
129
+ "wthek": {
130
+ "command": "npx",
131
+ "args": ["@wthek/mcp"]
132
+ }
133
+ }
134
+ }
135
+ ```
136
+
137
+ > ⚠️ **Security Note:** Do not use `npx -y` for MCP server commands. Always install packages explicitly with `npm install` before running them via `npx`, or review the confirmation prompt when `npx` asks to install a new package. This prevents unvetted code from auto-executing in your environment.
138
+
139
+ ### Available Tools
140
+
141
+ | Tool | Purpose |
142
+ | :--- | :--- |
143
+ | `lookup_http_status` | Returns RFC status metadata, required response headers, and class imports for any HTTP status code or name. |
144
+ | `get_framework_recipe` | Generates verified, copy-paste error handling recipes for Express, Fastify, Hono, Koa, NestJS, and Restify. |
145
+ | `audit_error_handling` | Performs pattern-based heuristic code audits to flag manual status mutations, swallowed logs, or missing `headersSent` checks. |
146
+
147
+ > ℹ️ **Heuristic Audit Disclaimer:** `audit_error_handling` is a fast pattern-based heuristic check for common error-handling anti-patterns. It is intentionally lightweight and non-intrusive—not a full AST-based static compiler or replacement for developer review or AI contextual reasoning.
148
+
@@ -0,0 +1,84 @@
1
+ # NestJS Error Handling with @wthek
2
+
3
+ Guide for implementing `@wthek/nestjs-middleware`.
4
+
5
+ ---
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ npm install @wthek/nestjs-middleware http-error-kit http-response-status-code
11
+ ```
12
+
13
+ Also ensure the underlying platform adapter package is installed:
14
+ - For Express (default): `@wthek/express-middleware`
15
+ - For Fastify: `@wthek/fastify-middleware`
16
+
17
+ ---
18
+
19
+ ## 1. Global Filter Registration (in `main.ts`)
20
+
21
+ NestJS applications can apply `KitExceptionFilter` globally. The filter automatically detects whether your application is running on the **Express** or **Fastify** adapter:
22
+
23
+ ```typescript
24
+ import { NestFactory } from "@nestjs/core";
25
+ import { AppModule } from "./app.module";
26
+ import { KitExceptionFilter } from "@wthek/nestjs-middleware";
27
+
28
+ async function bootstrap() {
29
+ const app = await NestFactory.create(AppModule);
30
+
31
+ // Apply the Kit exception filter globally with options
32
+ app.useGlobalFilters(
33
+ new KitExceptionFilter({
34
+ log: true,
35
+ handleUnknownErrors: true,
36
+ })
37
+ );
38
+
39
+ await app.listen(3000);
40
+ }
41
+ bootstrap();
42
+ ```
43
+
44
+ ---
45
+
46
+ ## 2. Module Provider Registration (in `app.module.ts`)
47
+
48
+ Alternatively, register the filter as an `APP_FILTER` provider to allow dependency injection (such as custom NestJS loggers):
49
+
50
+ ```typescript
51
+ import { Module } from "@nestjs/common";
52
+ import { APP_FILTER } from "@nestjs/core";
53
+ import { KitExceptionFilter } from "@wthek/nestjs-middleware";
54
+
55
+ @Module({
56
+ providers: [
57
+ {
58
+ provide: APP_FILTER,
59
+ useValue: new KitExceptionFilter({
60
+ log: (error, req) => {
61
+ console.error("NestJS Error caught:", error);
62
+ },
63
+ handleUnknownErrors: true,
64
+ }),
65
+ },
66
+ ],
67
+ })
68
+ export class AppModule {}
69
+ ```
70
+
71
+ ---
72
+
73
+ ## Options Reference
74
+
75
+ ```typescript
76
+ interface IKitNestJsMiddlewareOptions {
77
+ // Optional logger flag or custom callback:
78
+ log?: boolean | ((error: unknown, req: unknown) => void);
79
+
80
+ // When true, wraps unexpected runtime errors in a structured 500 JSON response:
81
+ handleUnknownErrors?: boolean;
82
+ }
83
+ ```
84
+
@@ -0,0 +1,68 @@
1
+ # Restify Error Handling with @wthek
2
+
3
+ Guide for implementing `@wthek/restify-middleware`.
4
+
5
+ ---
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ npm install @wthek/restify-middleware http-error-kit http-response-status-code
11
+ ```
12
+
13
+ ---
14
+
15
+ ## Usage in Restify Server
16
+
17
+ In Restify, error handling is configured using server events (`restify.server.on("restifyError", ...)`):
18
+
19
+ ```typescript
20
+ import restify from "restify";
21
+ import { KitRestifyMiddleware } from "@wthek/restify-middleware";
22
+ import { KitHttpError } from "http-error-kit";
23
+ import { NOT_FOUND } from "http-response-status-code";
24
+
25
+ const server = restify.createServer();
26
+ server.use(restify.plugins.bodyParser());
27
+
28
+ server.get("/user/:id", (req, res, next) => {
29
+ // Throwing or returning a KitHttpError
30
+ return next(new KitHttpError(NOT_FOUND, "User not found"));
31
+ });
32
+
33
+ // Attach KitRestifyMiddleware to the restifyError event
34
+ server.on(
35
+ "restifyError",
36
+ KitRestifyMiddleware({
37
+ log: true,
38
+ handleUnknownErrors: true,
39
+ })
40
+ );
41
+
42
+ server.listen(8080, () => {
43
+ console.log("Restify server running on port 8080");
44
+ });
45
+ ```
46
+
47
+ ---
48
+
49
+ ## Options Reference
50
+
51
+ ```typescript
52
+ interface IKitRestifyMiddlewareOptions {
53
+ // When true, logs via console.error.
54
+ // When a callback is provided, receives (error: unknown, req: restify.Request).
55
+ log?: boolean | ((error: unknown, req: restify.Request) => void);
56
+
57
+ // When true, catches any uncaught non-KitHttpError and formats as a structured 500 JSON response.
58
+ handleUnknownErrors?: boolean;
59
+ }
60
+ ```
61
+
62
+ ---
63
+
64
+ ## Key Differences from Express
65
+ - In Restify, errors are passed via `return next(error)` rather than `throw` in callback routes.
66
+ - Error handling is event-driven via `server.on("restifyError", ...)`.
67
+ - Built-in `res.headersSent` protection prevents double-reply crashes.
68
+
@@ -0,0 +1,181 @@
1
+ # http-response-status-code Usage Guide
2
+
3
+ Comprehensive reference for `http-response-status-code` — the companion status code package for the @wthek ecosystem.
4
+
5
+ ---
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ npm install http-response-status-code
11
+ ```
12
+
13
+ ---
14
+
15
+ ## Import Patterns
16
+
17
+ ```typescript
18
+ // ESM — named imports (tree-shaking friendly)
19
+ import { OK, NOT_FOUND, CREATED, UNPROCESSABLE_ENTITY } from "http-response-status-code";
20
+
21
+ // CJS
22
+ const { OK, NOT_FOUND } = require("http-response-status-code");
23
+
24
+ // CODES enum (alternative — all codes via single import)
25
+ import { CODES } from "http-response-status-code";
26
+ CODES.HTTP_CODE_404; // 404
27
+ CODES.HTTP_CODE_200; // 200
28
+
29
+ // Utility functions
30
+ import { getStatusName, getStatusDescription, toResponseInit, isClientError } from "http-response-status-code";
31
+ ```
32
+
33
+ ---
34
+
35
+ ## Usage with http-error-kit
36
+
37
+ ### Throwing Errors
38
+
39
+ ```typescript
40
+ import { KitHttpError } from "http-error-kit";
41
+ import { NOT_FOUND, BAD_REQUEST, CONFLICT } from "http-response-status-code";
42
+
43
+ throw new KitHttpError(NOT_FOUND, "User not found");
44
+ throw new KitHttpError(BAD_REQUEST, "Missing required field", { field: "email" });
45
+ throw new KitHttpError(CONFLICT, "Email already registered");
46
+ ```
47
+
48
+ ### With Validation Transformers
49
+
50
+ ```typescript
51
+ import { KitZodTransformer } from "@wthek/zod-transformer";
52
+ import { KitValibotTransformer } from "@wthek/valibot-transformer";
53
+ import { KitTypeBoxTransformer } from "@wthek/typebox-transformer";
54
+ import { UNPROCESSABLE_ENTITY } from "http-response-status-code";
55
+
56
+ // All transformers accept statusCode option
57
+ KitZodTransformer(err, { statusCode: UNPROCESSABLE_ENTITY });
58
+ KitValibotTransformer(err, { statusCode: UNPROCESSABLE_ENTITY });
59
+ KitTypeBoxTransformer(err, { statusCode: UNPROCESSABLE_ENTITY });
60
+ ```
61
+
62
+ ### Success Responses
63
+
64
+ ```typescript
65
+ import { CREATED, NO_CONTENT, OK } from "http-response-status-code";
66
+
67
+ res.status(CREATED).json({ user }); // 201
68
+ res.status(NO_CONTENT).send(); // 204
69
+ return c.json({ data }, OK); // 200
70
+ ```
71
+
72
+ ---
73
+
74
+ ## Utility Functions
75
+
76
+ ### `getStatusDescription(code)` — Human-Readable Names
77
+
78
+ ```typescript
79
+ import { getStatusDescription } from "http-response-status-code";
80
+
81
+ getStatusDescription(200); // "OK"
82
+ getStatusDescription(404); // "Not Found"
83
+ getStatusDescription(500); // "Internal Server Error"
84
+ getStatusDescription(422); // "Unprocessable Entity"
85
+ ```
86
+
87
+ ### `getStatusName(code)` — Constant Name Lookup
88
+
89
+ ```typescript
90
+ import { getStatusName } from "http-response-status-code";
91
+
92
+ getStatusName(404); // "NOT_FOUND"
93
+ getStatusName(418); // "IM_A_TEAPOT"
94
+ ```
95
+
96
+ ### `getStatusCode(name)` — Reverse Lookup
97
+
98
+ ```typescript
99
+ import { getStatusCode } from "http-response-status-code";
100
+
101
+ getStatusCode("NOT_FOUND"); // 404
102
+ getStatusCode("IM_A_TEAPOT"); // 418
103
+ ```
104
+
105
+ ### `toResponseInit(code, init?)` — Fetch API Helper
106
+
107
+ Creates a `{ status, statusText, ...init }` object compatible with the Fetch `Response` constructor:
108
+
109
+ ```typescript
110
+ import { toResponseInit, OK, NOT_FOUND } from "http-response-status-code";
111
+
112
+ // Basic
113
+ new Response("Hello", toResponseInit(OK));
114
+ // → Response with status: 200, statusText: "OK"
115
+
116
+ // With headers
117
+ new Response(body, toResponseInit(NOT_FOUND, {
118
+ headers: { "Content-Type": "application/json" },
119
+ }));
120
+
121
+ // Response.json() shorthand (Hono, Next.js App Router, Deno, Bun)
122
+ return Response.json({ data }, toResponseInit(OK));
123
+ return Response.json({ error: "not found" }, toResponseInit(NOT_FOUND));
124
+
125
+ // Accepts string name too
126
+ toResponseInit("OK"); // { status: 200, statusText: "OK" }
127
+ ```
128
+
129
+ ### Category Validators
130
+
131
+ ```typescript
132
+ import {
133
+ isInformational, isSuccess, isRedirectional,
134
+ isClientError, isServerError, isValidStatusCode,
135
+ } from "http-response-status-code";
136
+
137
+ isClientError(404); // true
138
+ isServerError(500); // true
139
+ isSuccess(200); // true
140
+ isValidStatusCode(999); // false (safe — doesn't throw)
141
+ isClientError(999); // ⚠️ THROWS — use isValidStatusCode() first!
142
+ ```
143
+
144
+ > **Warning:** All `is*` validators except `isValidStatusCode` **throw** for unrecognized codes.
145
+
146
+ ### Category Listers
147
+
148
+ ```typescript
149
+ import { getClientErrorCodes, getServerErrorCodes } from "http-response-status-code";
150
+
151
+ getClientErrorCodes(); // [400, 401, 402, ..., 451]
152
+ getServerErrorCodes(); // [500, 501, 502, ..., 511]
153
+ ```
154
+
155
+ ---
156
+
157
+ ## Common Patterns
158
+
159
+ ### Dynamic Error Messages
160
+
161
+ ```typescript
162
+ import { getStatusDescription } from "http-response-status-code";
163
+
164
+ function createError(statusCode: number, detail?: string) {
165
+ const message = detail ?? getStatusDescription(statusCode);
166
+ return new KitHttpError(statusCode, message);
167
+ }
168
+ ```
169
+
170
+ ### Conditional Response Handling
171
+
172
+ ```typescript
173
+ import { isClientError, isServerError } from "http-response-status-code";
174
+
175
+ if (isClientError(error.statusCode)) {
176
+ logger.warn("Client error", error);
177
+ } else if (isServerError(error.statusCode)) {
178
+ logger.error("Server error", error);
179
+ alertOps(error);
180
+ }
181
+ ```