@wthek/error-handling 0.0.0-stage → 1.0.0-beta.1

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 +139 -0
  6. package/dist/index.d.ts +23 -0
  7. package/dist/index.d.ts.map +1 -0
  8. package/dist/index.js +68 -0
  9. package/dist/installer.d.ts +43 -0
  10. package/dist/installer.d.ts.map +1 -0
  11. package/dist/installer.js +177 -0
  12. package/dist/types.d.ts +36 -0
  13. package/dist/types.d.ts.map +1 -0
  14. package/dist/types.js +2 -0
  15. package/package.json +102 -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,44 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const express_1 = require("express");
4
+ const zod_1 = require("zod");
5
+ const express_middleware_1 = require("@wthek/express-middleware");
6
+ const zod_express_interceptor_1 = require("@wthek/zod-express-interceptor");
7
+ const http_error_kit_1 = require("http-error-kit");
8
+ const http_response_status_code_1 = require("http-response-status-code");
9
+ // 1. Optional: Global response formatter
10
+ http_error_kit_1.KitHttpErrorConfig.configureFormatter((statusCode, message, details) => ({
11
+ status: statusCode,
12
+ error: message,
13
+ details: details ?? null,
14
+ }));
15
+ const app = (0, express_1.default)();
16
+ app.use(express_1.default.json());
17
+ // 2. Application routes
18
+ app.post("/register", (req, res) => {
19
+ const registerSchema = zod_1.z.object({
20
+ username: zod_1.z.string().min(3),
21
+ email: zod_1.z.string().email(),
22
+ });
23
+ const user = registerSchema.parse(req.body);
24
+ res.status(201).json({ status: "created", user });
25
+ });
26
+ app.get("/items/:id", (req, res) => {
27
+ if (req.params.id !== "42") {
28
+ throw new http_error_kit_1.KitHttpError(http_response_status_code_1.NOT_FOUND, "Item not found", { id: req.params.id });
29
+ }
30
+ res.json({ id: 42, name: "Special Item" });
31
+ });
32
+ // 3. Interceptors (MUST be placed after routes)
33
+ app.use((0, zod_express_interceptor_1.KitZodExpressInterceptor)({
34
+ message: "Validation failed on payload",
35
+ statusCode: http_response_status_code_1.UNPROCESSABLE_ENTITY,
36
+ }));
37
+ // 4. Terminal error handler
38
+ app.use((0, express_middleware_1.KitExpressMiddleware)({
39
+ log: true,
40
+ handleUnknownErrors: true,
41
+ }));
42
+ app.listen(3000, () => {
43
+ console.log("Server listening at http://localhost:3000");
44
+ });
@@ -0,0 +1,51 @@
1
+ import express from "express";
2
+ import { z } from "zod";
3
+ import { KitExpressMiddleware } from "@wthek/express-middleware";
4
+ import { KitZodExpressInterceptor } from "@wthek/zod-express-interceptor";
5
+ import { KitHttpError, KitHttpErrorConfig } from "http-error-kit";
6
+ import { NOT_FOUND, UNPROCESSABLE_ENTITY } from "http-response-status-code";
7
+
8
+ // 1. Optional: Global response formatter
9
+ KitHttpErrorConfig.configureFormatter((statusCode, message, details) => ({
10
+ status: statusCode,
11
+ error: message,
12
+ details: details ?? null,
13
+ }));
14
+
15
+ const app = express();
16
+ app.use(express.json());
17
+
18
+ // 2. Application routes
19
+ app.post("/register", (req, res) => {
20
+ const registerSchema = z.object({
21
+ username: z.string().min(3),
22
+ email: z.string().email(),
23
+ });
24
+
25
+ const user = registerSchema.parse(req.body);
26
+ res.status(201).json({ status: "created", user });
27
+ });
28
+
29
+ app.get("/items/:id", (req, res) => {
30
+ if (req.params.id !== "42") {
31
+ throw new KitHttpError(NOT_FOUND, "Item not found", { id: req.params.id });
32
+ }
33
+ res.json({ id: 42, name: "Special Item" });
34
+ });
35
+
36
+ // 3. Interceptors (MUST be placed after routes)
37
+ app.use(KitZodExpressInterceptor({
38
+ message: "Validation failed on payload",
39
+ statusCode: UNPROCESSABLE_ENTITY,
40
+ }));
41
+
42
+ // 4. Terminal error handler
43
+ app.use(KitExpressMiddleware({
44
+ log: true,
45
+ handleUnknownErrors: true,
46
+ }));
47
+
48
+ app.listen(3000, () => {
49
+ console.log("Server listening at http://localhost:3000");
50
+ });
51
+
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const fastify_1 = require("fastify");
4
+ const zod_1 = require("zod");
5
+ const fastify_middleware_1 = require("@wthek/fastify-middleware");
6
+ const zod_transformer_1 = require("@wthek/zod-transformer");
7
+ const http_error_kit_1 = require("http-error-kit");
8
+ const http_response_status_code_1 = require("http-response-status-code");
9
+ const app = (0, fastify_1.default)({ logger: true });
10
+ // Schema definition
11
+ const loginSchema = zod_1.z.object({
12
+ email: zod_1.z.string().email(),
13
+ password: zod_1.z.string().min(8),
14
+ });
15
+ app.post("/login", async (req) => {
16
+ const parseResult = loginSchema.safeParse(req.body);
17
+ if (!parseResult.success) {
18
+ // Transform ZodError into KitHttpError
19
+ const error = (0, zod_transformer_1.fromZodError)(parseResult.error, {
20
+ message: "Invalid login credentials format",
21
+ statusCode: http_response_status_code_1.UNPROCESSABLE_ENTITY,
22
+ });
23
+ throw error;
24
+ }
25
+ return { token: "sample-jwt-token" };
26
+ });
27
+ app.get("/profile", async () => {
28
+ throw new http_error_kit_1.KitHttpError(http_response_status_code_1.NOT_FOUND, "Profile not found");
29
+ });
30
+ // Attach global WTHek Fastify error handler
31
+ (0, fastify_middleware_1.KitFastifyMiddleware)(app, {
32
+ log: true,
33
+ handleUnknownErrors: true,
34
+ });
35
+ app.listen({ port: 3000 }, (err) => {
36
+ if (err) {
37
+ app.log.error(err);
38
+ process.exit(1);
39
+ }
40
+ });
@@ -0,0 +1,45 @@
1
+ import Fastify from "fastify";
2
+ import { z } from "zod";
3
+ import { KitFastifyMiddleware } from "@wthek/fastify-middleware";
4
+ import { fromZodError } from "@wthek/zod-transformer";
5
+ import { KitHttpError } from "http-error-kit";
6
+ import { NOT_FOUND, UNPROCESSABLE_ENTITY } from "http-response-status-code";
7
+
8
+ const app = Fastify({ logger: true });
9
+
10
+ // Schema definition
11
+ const loginSchema = z.object({
12
+ email: z.string().email(),
13
+ password: z.string().min(8),
14
+ });
15
+
16
+ app.post("/login", async (req) => {
17
+ const parseResult = loginSchema.safeParse(req.body);
18
+ if (!parseResult.success) {
19
+ // Transform ZodError into KitHttpError
20
+ const error = fromZodError(parseResult.error, {
21
+ message: "Invalid login credentials format",
22
+ statusCode: UNPROCESSABLE_ENTITY,
23
+ });
24
+ throw error;
25
+ }
26
+ return { token: "sample-jwt-token" };
27
+ });
28
+
29
+ app.get("/profile", async () => {
30
+ throw new KitHttpError(NOT_FOUND, "Profile not found");
31
+ });
32
+
33
+ // Attach global WTHek Fastify error handler
34
+ KitFastifyMiddleware(app, {
35
+ log: true,
36
+ handleUnknownErrors: true,
37
+ });
38
+
39
+ app.listen({ port: 3000 }, (err) => {
40
+ if (err) {
41
+ app.log.error(err);
42
+ process.exit(1);
43
+ }
44
+ });
45
+
@@ -0,0 +1,42 @@
1
+ import { Hono } from "hono";
2
+ import { KitHonoMiddleware } from "@wthek/hono-middleware";
3
+ import { KitValibotTransformer } from "@wthek/valibot-transformer";
4
+ import { KitHttpError } from "http-error-kit";
5
+ import { NOT_FOUND, UNPROCESSABLE_ENTITY, CREATED } from "http-response-status-code";
6
+ import * as v from "valibot";
7
+
8
+ const app = new Hono();
9
+
10
+ // 1. Attach global error handler
11
+ KitHonoMiddleware(app, {
12
+ log: true,
13
+ handleUnknownErrors: true,
14
+ });
15
+
16
+ // 2. Schema definition
17
+ const UserSchema = v.object({
18
+ username: v.pipe(v.string(), v.minLength(3, "Username must be at least 3 characters")),
19
+ email: v.pipe(v.string(), v.email("Invalid email address")),
20
+ });
21
+
22
+ // 3. Routes
23
+ app.post("/users", async (c) => {
24
+ const body = await c.req.json();
25
+ try {
26
+ const user = v.parse(UserSchema, body);
27
+ return c.json({ status: "success", data: user }, CREATED);
28
+ } catch (err) {
29
+ KitValibotTransformer(err, { statusCode: UNPROCESSABLE_ENTITY });
30
+ }
31
+ });
32
+
33
+ app.get("/users/:id", (c) => {
34
+ const id = c.req.param("id");
35
+ if (id !== "42") {
36
+ throw new KitHttpError(NOT_FOUND, "User not found", { userId: id });
37
+ }
38
+ return c.json({ id: "42", username: "alex" });
39
+ });
40
+
41
+ export default app;
42
+
@@ -0,0 +1,54 @@
1
+ import Koa from "koa";
2
+ import bodyParser from "koa-bodyparser";
3
+ import { KitKoaMiddleware } from "@wthek/koa-middleware";
4
+ import { KitTypeBoxTransformer } from "@wthek/typebox-transformer";
5
+ import { KitHttpError } from "http-error-kit";
6
+ import { NOT_FOUND, UNPROCESSABLE_ENTITY, CREATED } from "http-response-status-code";
7
+ import { Type, Static } from "@sinclair/typebox";
8
+ import { Value } from "@sinclair/typebox/value";
9
+
10
+ const app = new Koa();
11
+
12
+ // 1. Error middleware MUST be mounted at the top of the Koa stack
13
+ app.use(
14
+ KitKoaMiddleware({
15
+ log: true,
16
+ handleUnknownErrors: true,
17
+ emitAppError: true,
18
+ })
19
+ );
20
+
21
+ app.use(bodyParser());
22
+
23
+ // 2. Schema definition
24
+ const CreateItemSchema = Type.Object({
25
+ title: Type.String({ minLength: 3 }),
26
+ price: Type.Number({ minimum: 0 }),
27
+ });
28
+
29
+ type CreateItemDto = Static<typeof CreateItemSchema>;
30
+
31
+ // 3. Application routes
32
+ app.use(async (ctx) => {
33
+ if (ctx.method === "POST" && ctx.path === "/items") {
34
+ try {
35
+ Value.Assert(CreateItemSchema, ctx.request.body);
36
+ const data = ctx.request.body as CreateItemDto;
37
+ ctx.status = CREATED;
38
+ ctx.body = { status: "created", item: data };
39
+ } catch (err: unknown) {
40
+ KitTypeBoxTransformer(err, { statusCode: UNPROCESSABLE_ENTITY });
41
+ }
42
+ return;
43
+ }
44
+
45
+ if (ctx.method === "GET" && ctx.path === "/items/1") {
46
+ ctx.body = { id: 1, title: "Standard Item", price: 29.99 };
47
+ return;
48
+ }
49
+
50
+ throw new KitHttpError(NOT_FOUND, "Route not found", { path: ctx.path });
51
+ });
52
+
53
+ export default app;
54
+
@@ -0,0 +1,73 @@
1
+ # Express.js Error Handling with @wthek
2
+
3
+ Guide for implementing `@wthek/express-middleware` and `@wthek/zod-express-interceptor`.
4
+
5
+ ---
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ npm install @wthek/express-middleware @wthek/zod-express-interceptor http-error-kit http-response-status-code
11
+ ```
12
+
13
+ ## Production Recipe
14
+
15
+ ```typescript
16
+ import express from "express";
17
+ import { z } from "zod";
18
+ import { KitExpressMiddleware } from "@wthek/express-middleware";
19
+ import { KitZodExpressInterceptor } from "@wthek/zod-express-interceptor";
20
+ import { KitHttpError } from "http-error-kit";
21
+ import { NOT_FOUND, UNPROCESSABLE_ENTITY } from "http-response-status-code";
22
+
23
+ const app = express();
24
+ app.use(express.json());
25
+
26
+ // Routes
27
+ app.post("/users", (req, res) => {
28
+ const userSchema = z.object({
29
+ email: z.string().email(),
30
+ age: z.number().min(18),
31
+ });
32
+
33
+ const validated = userSchema.parse(req.body);
34
+ res.status(201).json({ success: true, data: validated });
35
+ });
36
+
37
+ app.get("/users/:id", (req, res) => {
38
+ // Manually throwing a KitHttpError
39
+ throw new KitHttpError(NOT_FOUND, "User not found", { userId: req.params.id });
40
+ });
41
+
42
+ // 1. Intercept Zod validation errors (MUST be after routes)
43
+ app.use(KitZodExpressInterceptor({
44
+ message: "Invalid request payload",
45
+ statusCode: UNPROCESSABLE_ENTITY, // 422
46
+ }));
47
+
48
+ // 2. Final Error Handler (MUST be the last middleware)
49
+ app.use(KitExpressMiddleware({
50
+ log: (err, req) => console.error(`[Error on ${req.method} ${req.url}]:`, err),
51
+ handleUnknownErrors: true, // Safely turns uncaught exceptions into 500 JSON
52
+ }));
53
+
54
+ app.listen(3000, () => console.log("Server listening on port 3000"));
55
+ ```
56
+
57
+ ## Options Reference
58
+
59
+ ```typescript
60
+ app.use(KitExpressMiddleware({
61
+ // Enable simple console.error logging:
62
+ log: true,
63
+
64
+ // OR custom logger callback (e.g. Pino/Winston):
65
+ log: (error: unknown, req: express.Request) => {
66
+ logger.error({ err: error, path: req.path }, "API error occurred");
67
+ },
68
+
69
+ // Catch non-Kit errors (Error, TypeError, etc.) and return structured 500:
70
+ handleUnknownErrors: true,
71
+ }));
72
+ ```
73
+
@@ -0,0 +1,81 @@
1
+ # Fastify Error Handling with @wthek
2
+
3
+ Guide for implementing `@wthek/fastify-middleware`.
4
+
5
+ ---
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ npm install @wthek/fastify-middleware http-error-kit http-response-status-code
11
+ ```
12
+
13
+ ## Two Modes of Usage
14
+
15
+ `@wthek/fastify-middleware` supports two approaches depending on whether you are configuring the global application instance or a scoped plugin context:
16
+
17
+ ### 1. Global Setup (`KitFastifyMiddleware`)
18
+
19
+ Attaches the error handler directly across the entire Fastify application instance:
20
+
21
+ ```typescript
22
+ import Fastify from "fastify";
23
+ import { KitFastifyMiddleware } from "@wthek/fastify-middleware";
24
+
25
+ const app = Fastify({ logger: true });
26
+
27
+ // Setup routes
28
+ app.get("/items", async () => {
29
+ // route logic
30
+ });
31
+
32
+ // Configure global error handler
33
+ KitFastifyMiddleware(app, {
34
+ log: true, // Uses Fastify's built-in Pino logger (request.log.error)
35
+ handleUnknownErrors: true, // Converts unexpected runtime crashes to 500 JSON
36
+ });
37
+
38
+ await app.listen({ port: 3000 });
39
+ ```
40
+
41
+ ### 2. Scoped Plugin Setup (`KitFastifyErrorHandler`)
42
+
43
+ Returns a pure error-handling function compatible with `fastify.setErrorHandler` or encapsulated plugins:
44
+
45
+ ```typescript
46
+ import Fastify from "fastify";
47
+ import { KitFastifyErrorHandler } from "@wthek/fastify-middleware";
48
+
49
+ const app = Fastify();
50
+
51
+ // Use directly in setErrorHandler
52
+ app.setErrorHandler(
53
+ KitFastifyErrorHandler({
54
+ log: (err, req) => req.log.error({ err }, "Custom error message"),
55
+ handleUnknownErrors: true,
56
+ })
57
+ );
58
+
59
+ // Or inside a scoped Fastify plugin
60
+ app.register(async function apiV1(instance) {
61
+ instance.setErrorHandler(KitFastifyErrorHandler());
62
+
63
+ instance.get("/test", async () => {
64
+ // ...
65
+ });
66
+ }, { prefix: "/api/v1" });
67
+ ```
68
+
69
+ ## Options Reference
70
+
71
+ ```typescript
72
+ interface IKitFastifyMiddlewareOptions {
73
+ // When true, uses Fastify's built-in Pino logger (`request.log.error`).
74
+ // When a callback is provided, receives (error: unknown, req: FastifyRequest).
75
+ log?: boolean | ((error: unknown, req: FastifyRequest) => void);
76
+
77
+ // When true, catches any uncaught non-KitHttpError and formats as a 500 response.
78
+ handleUnknownErrors?: boolean;
79
+ }
80
+ ```
81
+
@@ -0,0 +1,241 @@
1
+ # Custom Formatters, RFC-7807/RFC-9457 & MCP Alignment
2
+
3
+ Guide for formatting error responses into standardized formats using `http-error-kit` formatters.
4
+
5
+ ---
6
+
7
+ ## How Formatters Work
8
+
9
+ All `@wthek` middleware packages serialize errors by calling `error.toJSON()` (Express uses `res.send(error)` which triggers `toJSON()`; Hono/Koa use `c.json(error.toJSON())` / `ctx.body = error.toJSON()`). The **formatter** controls what `toJSON()` returns.
10
+
11
+ **Without a formatter**, the default output is:
12
+ ```json
13
+ { "statusCode": 400, "message": "Bad Request", "details": null }
14
+ ```
15
+
16
+ **With a formatter**, you control the shape entirely.
17
+
18
+ ### Formatter Function Signature
19
+
20
+ ```typescript
21
+ type IFormatter = (
22
+ statusCode: number,
23
+ message: string,
24
+ details: unknown,
25
+ ...args: unknown[]
26
+ ) => unknown;
27
+ ```
28
+
29
+ The `args` are additional arguments passed to `new KitHttpError(statusCode, message, details, ...args)`.
30
+
31
+ ---
32
+
33
+ ## Global Formatter Configuration
34
+
35
+ Configure once at server startup. Applies to **all** `KitHttpError` instances:
36
+
37
+ ```typescript
38
+ import { KitHttpErrorConfig } from "http-error-kit";
39
+
40
+ KitHttpErrorConfig.configureFormatter((statusCode, message, details, ...args) => {
41
+ return {
42
+ success: false,
43
+ status: statusCode,
44
+ error: {
45
+ message,
46
+ details: details ?? null,
47
+ timestamp: new Date().toISOString(),
48
+ traceId: args[0] ?? null,
49
+ },
50
+ };
51
+ });
52
+ ```
53
+
54
+ ### Resetting the Formatter
55
+
56
+ ```typescript
57
+ KitHttpErrorConfig.resetFormatter();
58
+ ```
59
+
60
+ This clears the global formatter **and** disables `KitHttpError`-based error mode (reverts to `KitGeneralError` for the default import path).
61
+
62
+ ---
63
+
64
+ ## Instance-Specific Formatter
65
+
66
+ Override the global format for a specific error. Returns `this` for chaining:
67
+
68
+ ```typescript
69
+ import { KitHttpError } from "http-error-kit";
70
+ import { BAD_REQUEST } from "http-response-status-code";
71
+
72
+ const error = new KitHttpError(BAD_REQUEST, "Payment failed", { code: "CARD_DECLINED" });
73
+
74
+ error.setFormatter((statusCode, message, details) => ({
75
+ error_code: (details as any)?.code,
76
+ error_description: message,
77
+ }));
78
+
79
+ throw error;
80
+ ```
81
+
82
+ ---
83
+
84
+ ## RFC-7807 Problem Details (application/problem+json)
85
+
86
+ [RFC 7807](https://datatracker.ietf.org/doc/html/rfc7807) defines a standard JSON format for HTTP error responses. Its successor [RFC 9457](https://datatracker.ietf.org/doc/html/rfc9457) refines and obsoletes it but maintains backward compatibility.
87
+
88
+ ### Required Fields
89
+
90
+ | Field | Type | Description |
91
+ | :--- | :--- | :--- |
92
+ | `type` | `string` (URI) | A URI reference identifying the error type. Use `"about:blank"` when no specific type URI exists. |
93
+ | `title` | `string` | A short, human-readable summary. Should NOT change between occurrences. |
94
+ | `status` | `number` | The HTTP status code. |
95
+
96
+ ### Optional Fields
97
+
98
+ | Field | Type | Description |
99
+ | :--- | :--- | :--- |
100
+ | `detail` | `string` | Human-readable explanation specific to this occurrence. |
101
+ | `instance` | `string` (URI) | A URI reference identifying the specific occurrence (e.g., request URL, trace ID). |
102
+
103
+ ### Built-In RFC-7807 Formatter (Recommended)
104
+
105
+ `http-error-kit` provides a built-in RFC-7807 / RFC-9457 formatter and activation helper:
106
+
107
+ ```typescript
108
+ import { KitHttpErrorConfig, rfcProblemDetailsFormatter } from "http-error-kit";
109
+
110
+ // One-liner activation:
111
+ KitHttpErrorConfig.useRfcProblemDetails();
112
+
113
+ // Or explicitly configure with the exported formatter function:
114
+ // KitHttpErrorConfig.configureFormatter(rfcProblemDetailsFormatter);
115
+ ```
116
+
117
+ ### Custom RFC Formatter Implementation
118
+
119
+ If you need a custom base URI or custom extension members:
120
+
121
+ ```typescript
122
+ import { KitHttpErrorConfig } from "http-error-kit";
123
+
124
+ KitHttpErrorConfig.configureFormatter((statusCode, message, details, ...args) => {
125
+ return {
126
+ type: `https://httpstatuses.com/${statusCode}`,
127
+ title: message,
128
+ status: statusCode,
129
+ detail: typeof details === "string" ? details : undefined,
130
+ instance: typeof args[0] === "string" ? args[0] : undefined,
131
+ ...(typeof details === "object" && details !== null ? { invalidParams: details } : {}),
132
+ };
133
+ });
134
+ ```
135
+
136
+ ### RFC-9457 Enhancements
137
+
138
+ RFC 9457 (the successor to RFC 7807) adds:
139
+ - **`type` defaults to `"about:blank"`** when omitted (instead of being required)
140
+ - **Content-Type**: `application/problem+json` (same as RFC 7807)
141
+ - **Extension members**: Any additional JSON fields are allowed and encouraged
142
+
143
+ ```typescript
144
+ KitHttpErrorConfig.configureFormatter((statusCode, message, details, ...args) => ({
145
+ // RFC-9457 — type defaults to about:blank
146
+ type: "about:blank",
147
+ title: message,
148
+ status: statusCode,
149
+ detail: typeof details === "string" ? details : message,
150
+ instance: typeof args[0] === "string" ? args[0] : undefined,
151
+ // Extension: validation errors
152
+ ...(details && typeof details === "object" && "issues" in (details as object)
153
+ ? { errors: (details as { issues: unknown[] }).issues }
154
+ : {}),
155
+ }));
156
+ ```
157
+
158
+ ### Setting Content-Type Header
159
+
160
+ The `@wthek` middleware packages set `application/json` by default. For strict RFC compliance, set the header in your framework:
161
+
162
+ ```typescript
163
+ // Express — via a wrapper
164
+ app.use((err, req, res, next) => {
165
+ res.type("application/problem+json");
166
+ next(err);
167
+ });
168
+ app.use(KitExpressMiddleware());
169
+
170
+ // Hono — set in error handler
171
+ app.onError(KitHonoErrorHandler({ ... }));
172
+ // Or override with instance formatter that sets header
173
+ ```
174
+
175
+ ---
176
+
177
+ ## MCP Error Formatter (Planned)
178
+
179
+ The `@wthek/mcp-error-formatter` package (not yet published) will format `KitHttpError` instances into [MCP (Model Context Protocol)](https://modelcontextprotocol.io/) error responses.
180
+
181
+ ### Planned Design
182
+
183
+ The MCP error format maps to JSON-RPC 2.0 error responses used by MCP:
184
+
185
+ ```json
186
+ {
187
+ "jsonrpc": "2.0",
188
+ "error": {
189
+ "code": -32603,
190
+ "message": "Internal Server Error",
191
+ "data": { "statusCode": 500, "details": null }
192
+ },
193
+ "id": 1
194
+ }
195
+ ```
196
+
197
+ ### Alignment Strategy
198
+
199
+ The MCP formatter will:
200
+ 1. Map HTTP status codes to appropriate JSON-RPC error codes
201
+ 2. Preserve `KitHttpError` details in the `data` field
202
+ 3. Follow the same `KitHttpErrorConfig.configureFormatter()` pattern
203
+ 4. Allow dual-output formatters that work for both HTTP and MCP transports
204
+
205
+ ### Dual-Transport Formatter Pattern (Preview)
206
+
207
+ When the MCP formatter ships, you'll be able to write a single formatter that handles both:
208
+
209
+ ```typescript
210
+ import { KitHttpErrorConfig } from "http-error-kit";
211
+
212
+ KitHttpErrorConfig.configureFormatter((statusCode, message, details, ...args) => {
213
+ const transport = args[0]; // "http" | "mcp"
214
+
215
+ if (transport === "mcp") {
216
+ return {
217
+ code: statusCode >= 500 ? -32603 : -32602,
218
+ message,
219
+ data: { statusCode, details },
220
+ };
221
+ }
222
+
223
+ // Default: RFC-7807 for HTTP
224
+ return {
225
+ type: `https://httpstatuses.com/${statusCode}`,
226
+ title: message,
227
+ status: statusCode,
228
+ detail: typeof details === "string" ? details : undefined,
229
+ };
230
+ });
231
+ ```
232
+
233
+ ---
234
+
235
+ ## Formatter Priority Chain
236
+
237
+ When `toJSON()` is called on a `KitHttpError`:
238
+
239
+ 1. **Instance formatter** (set via `error.setFormatter(fn)`) — highest priority
240
+ 2. **Global formatter** (set via `KitHttpErrorConfig.configureFormatter(fn)`)
241
+ 3. **Default format** — `{ statusCode, message, details }`