@anvil-di/bellows 0.0.4 → 0.0.5

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.
@@ -0,0 +1,149 @@
1
+ import type { NextFunction, Request, Response } from "express";
2
+ import { describe, expect, it, vi } from "vitest";
3
+ import {
4
+ BadGatewayError,
5
+ BadRequestError,
6
+ ConflictError,
7
+ ForbiddenError,
8
+ GatewayTimeoutError,
9
+ GoneError,
10
+ HttpError,
11
+ InternalServerError,
12
+ MethodNotAllowedError,
13
+ NotAcceptableError,
14
+ NotFoundError,
15
+ NotImplementedError,
16
+ PayloadTooLargeError,
17
+ PreconditionFailedError,
18
+ RequestTimeoutError,
19
+ ServiceUnavailableError,
20
+ TooManyRequestsError,
21
+ UnauthorizedError,
22
+ UnprocessableEntityError,
23
+ UnsupportedMediaTypeError,
24
+ errorHandler,
25
+ } from "./errors.js";
26
+
27
+ // --- HttpError ---
28
+
29
+ describe("HttpError", () => {
30
+ it("uses `error` as the message when none is given", () => {
31
+ const err = new HttpError(400, "Bad Request");
32
+ expect(err.message).toBe("Bad Request");
33
+ expect(err.body()).toEqual({ error: "Bad Request" });
34
+ });
35
+
36
+ it("includes a distinct message in the body", () => {
37
+ const err = new HttpError(400, "Bad Request", "the `id` field is required");
38
+ expect(err.body()).toEqual({
39
+ error: "Bad Request",
40
+ message: "the `id` field is required",
41
+ });
42
+ });
43
+
44
+ it("sets `name` to the concrete subclass name", () => {
45
+ const err = new NotFoundError();
46
+ expect(err.name).toBe("NotFoundError");
47
+ expect(err).toBeInstanceOf(HttpError);
48
+ expect(err).toBeInstanceOf(Error);
49
+ });
50
+ });
51
+
52
+ // --- Subclasses map to the right status/error pair ---
53
+
54
+ describe("HttpError subclasses", () => {
55
+ const cases: Array<[new (message?: string) => HttpError, number, string]> = [
56
+ [BadRequestError, 400, "Bad Request"],
57
+ [UnauthorizedError, 401, "Unauthorized"],
58
+ [ForbiddenError, 403, "Forbidden"],
59
+ [NotFoundError, 404, "Not Found"],
60
+ [MethodNotAllowedError, 405, "Method Not Allowed"],
61
+ [NotAcceptableError, 406, "Not Acceptable"],
62
+ [RequestTimeoutError, 408, "Request Timeout"],
63
+ [ConflictError, 409, "Conflict"],
64
+ [GoneError, 410, "Gone"],
65
+ [PreconditionFailedError, 412, "Precondition Failed"],
66
+ [PayloadTooLargeError, 413, "Payload Too Large"],
67
+ [UnsupportedMediaTypeError, 415, "Unsupported Media Type"],
68
+ [UnprocessableEntityError, 422, "Unprocessable Entity"],
69
+ [TooManyRequestsError, 429, "Too Many Requests"],
70
+ [InternalServerError, 500, "Internal Server Error"],
71
+ [NotImplementedError, 501, "Not Implemented"],
72
+ [BadGatewayError, 502, "Bad Gateway"],
73
+ [ServiceUnavailableError, 503, "Service Unavailable"],
74
+ [GatewayTimeoutError, 504, "Gateway Timeout"],
75
+ ];
76
+
77
+ it.each(cases)("%s has status %d and error %j", (Ctor, status, error) => {
78
+ const err = new Ctor();
79
+ expect(err.status).toBe(status);
80
+ expect(err.error).toBe(error);
81
+ expect(err.body()).toEqual({ error });
82
+ });
83
+
84
+ it("passes through a custom message", () => {
85
+ const err = new NotFoundError("no user with that id");
86
+ expect(err.body()).toEqual({ error: "Not Found", message: "no user with that id" });
87
+ });
88
+ });
89
+
90
+ // --- errorHandler ---
91
+
92
+ function mockRes(): Response {
93
+ const res = {
94
+ headersSent: false,
95
+ status: vi.fn().mockReturnThis(),
96
+ json: vi.fn().mockReturnThis(),
97
+ end: vi.fn(),
98
+ };
99
+ return res as unknown as Response;
100
+ }
101
+
102
+ describe("errorHandler", () => {
103
+ it("maps an HttpError to its status and body", () => {
104
+ const res = mockRes();
105
+ const req = {} as Request;
106
+ errorHandler(new ForbiddenError("nope"), req, res, vi.fn() as NextFunction);
107
+
108
+ expect(res.status).toHaveBeenCalledWith(403);
109
+ expect(res.json).toHaveBeenCalledWith({ error: "Forbidden", message: "nope" });
110
+ });
111
+
112
+ it("falls back to a generic 500 for unknown errors", () => {
113
+ const res = mockRes();
114
+ const req = {} as Request;
115
+ errorHandler(new Error("some internal detail"), req, res, vi.fn() as NextFunction);
116
+
117
+ expect(res.status).toHaveBeenCalledWith(500);
118
+ expect(res.json).toHaveBeenCalledWith({
119
+ error: "Internal Server Error",
120
+ message: "Internal server error",
121
+ });
122
+ });
123
+
124
+ it("logs unknown errors via req.log when present", () => {
125
+ const res = mockRes();
126
+ const log = { error: vi.fn() };
127
+ const req = { log } as unknown as Request;
128
+ const err = new Error("boom");
129
+ errorHandler(err, req, res, vi.fn() as NextFunction);
130
+
131
+ expect(log.error).toHaveBeenCalledWith({ err }, "Unhandled error");
132
+ });
133
+
134
+ it("does not throw when req.log is absent", () => {
135
+ const res = mockRes();
136
+ const req = {} as Request;
137
+ expect(() => errorHandler(new Error("boom"), req, res, vi.fn() as NextFunction)).not.toThrow();
138
+ });
139
+
140
+ it("ends the response without writing a body if headers are already sent", () => {
141
+ const res = mockRes();
142
+ (res as { headersSent: boolean }).headersSent = true;
143
+ const req = {} as Request;
144
+ errorHandler(new NotFoundError(), req, res, vi.fn() as NextFunction);
145
+
146
+ expect(res.end).toHaveBeenCalled();
147
+ expect(res.status).not.toHaveBeenCalled();
148
+ });
149
+ });
package/src/errors.ts ADDED
@@ -0,0 +1,186 @@
1
+ import type { NextFunction, Request, Response } from "express";
2
+
3
+ /**
4
+ * HTTP error hierarchy for bellows controllers.
5
+ *
6
+ * bellows-generated route handlers do not catch exceptions, and Express 5
7
+ * forwards rejected promises from async handlers to the error middleware.
8
+ * So controller methods signal non-2xx outcomes by throwing one of these,
9
+ * and `errorHandler` (registered last on the app) maps them to a response.
10
+ */
11
+ export class HttpError extends Error {
12
+ constructor(
13
+ readonly status: number,
14
+ readonly error: string,
15
+ message?: string,
16
+ ) {
17
+ super(message ?? error);
18
+ this.name = new.target.name;
19
+ }
20
+
21
+ body(): Record<string, unknown> {
22
+ return this.message && this.message !== this.error
23
+ ? { error: this.error, message: this.message }
24
+ : { error: this.error };
25
+ }
26
+ }
27
+
28
+ export class BadRequestError extends HttpError {
29
+ constructor(message?: string) {
30
+ super(400, "Bad Request", message);
31
+ }
32
+ }
33
+
34
+ export class UnauthorizedError extends HttpError {
35
+ constructor(message?: string) {
36
+ super(401, "Unauthorized", message);
37
+ }
38
+ }
39
+
40
+ export class ForbiddenError extends HttpError {
41
+ constructor(message?: string) {
42
+ super(403, "Forbidden", message);
43
+ }
44
+ }
45
+
46
+ export class NotFoundError extends HttpError {
47
+ constructor(message?: string) {
48
+ super(404, "Not Found", message);
49
+ }
50
+ }
51
+
52
+ export class MethodNotAllowedError extends HttpError {
53
+ constructor(message?: string) {
54
+ super(405, "Method Not Allowed", message);
55
+ }
56
+ }
57
+
58
+ export class NotAcceptableError extends HttpError {
59
+ constructor(message?: string) {
60
+ super(406, "Not Acceptable", message);
61
+ }
62
+ }
63
+
64
+ export class RequestTimeoutError extends HttpError {
65
+ constructor(message?: string) {
66
+ super(408, "Request Timeout", message);
67
+ }
68
+ }
69
+
70
+ export class ConflictError extends HttpError {
71
+ constructor(message?: string) {
72
+ super(409, "Conflict", message);
73
+ }
74
+ }
75
+
76
+ export class GoneError extends HttpError {
77
+ constructor(message?: string) {
78
+ super(410, "Gone", message);
79
+ }
80
+ }
81
+
82
+ export class PreconditionFailedError extends HttpError {
83
+ constructor(message?: string) {
84
+ super(412, "Precondition Failed", message);
85
+ }
86
+ }
87
+
88
+ export class PayloadTooLargeError extends HttpError {
89
+ constructor(message?: string) {
90
+ super(413, "Payload Too Large", message);
91
+ }
92
+ }
93
+
94
+ export class UnsupportedMediaTypeError extends HttpError {
95
+ constructor(message?: string) {
96
+ super(415, "Unsupported Media Type", message);
97
+ }
98
+ }
99
+
100
+ export class UnprocessableEntityError extends HttpError {
101
+ constructor(message?: string) {
102
+ super(422, "Unprocessable Entity", message);
103
+ }
104
+ }
105
+
106
+ export class TooManyRequestsError extends HttpError {
107
+ constructor(message?: string) {
108
+ super(429, "Too Many Requests", message);
109
+ }
110
+ }
111
+
112
+ export class InternalServerError extends HttpError {
113
+ constructor(message?: string) {
114
+ super(500, "Internal Server Error", message);
115
+ }
116
+ }
117
+
118
+ export class NotImplementedError extends HttpError {
119
+ constructor(message?: string) {
120
+ super(501, "Not Implemented", message);
121
+ }
122
+ }
123
+
124
+ export class BadGatewayError extends HttpError {
125
+ constructor(message?: string) {
126
+ super(502, "Bad Gateway", message);
127
+ }
128
+ }
129
+
130
+ export class ServiceUnavailableError extends HttpError {
131
+ constructor(message?: string) {
132
+ super(503, "Service Unavailable", message);
133
+ }
134
+ }
135
+
136
+ export class GatewayTimeoutError extends HttpError {
137
+ constructor(message?: string) {
138
+ super(504, "Gateway Timeout", message);
139
+ }
140
+ }
141
+
142
+ /**
143
+ * Minimal structural type for a pino-style logger. `errorHandler` looks for
144
+ * `req.log` (as attached by e.g. `pino-http`) but does not depend on pino —
145
+ * anything satisfying this shape works, and unhandled errors are still
146
+ * caught if `req.log` is absent.
147
+ */
148
+ export interface RequestLogger {
149
+ error(obj: Record<string, unknown>, msg?: string): void;
150
+ }
151
+
152
+ export interface RequestWithLogger extends Request {
153
+ log?: RequestLogger;
154
+ }
155
+
156
+ /**
157
+ * Express error-handling middleware. Maps `HttpError` subclasses to their
158
+ * status and body. Falls back to 500 for anything unexpected, logging the
159
+ * full error via `req.log` (if present) while returning only a generic
160
+ * message to the caller — internal error text should never be echoed back,
161
+ * since it may embed request data the caller isn't entitled to see.
162
+ *
163
+ * Must be registered after all routes.
164
+ */
165
+ export function errorHandler(
166
+ err: unknown,
167
+ req: Request,
168
+ res: Response,
169
+ _next: NextFunction,
170
+ ): void {
171
+ // `_next` is required so Express recognizes this as error-handling middleware.
172
+ void _next;
173
+ if (res.headersSent) {
174
+ // Response already streaming (e.g. SSE) — let Express close the socket.
175
+ res.end();
176
+ return;
177
+ }
178
+
179
+ if (err instanceof HttpError) {
180
+ res.status(err.status).json(err.body());
181
+ return;
182
+ }
183
+
184
+ (req as RequestWithLogger).log?.error({ err }, "Unhandled error");
185
+ res.status(500).json({ error: "Internal Server Error", message: "Internal server error" });
186
+ }