@stacksjs/error-handling 0.70.57 → 0.70.58

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,373 @@
1
+ var {require}=import.meta;const DOCS_BASE = "https://stacksjs.org/docs/errors";
2
+ export const HTTP_ERRORS = {
3
+ 400: {
4
+ status: 400,
5
+ title: "Bad Request",
6
+ message: "The request was malformed or invalid.",
7
+ docLink: `${DOCS_BASE}/400`,
8
+ commonCauses: [
9
+ "JSON body is missing or has a syntax error",
10
+ "A required field is absent from the payload",
11
+ "Content-Type header does not match the body format"
12
+ ],
13
+ suggestion: "Inspect the request body and Content-Type \u2014 most 400s come from malformed JSON or a missing required field."
14
+ },
15
+ 401: {
16
+ status: 401,
17
+ title: "Unauthorized",
18
+ message: "Authentication is required to access this resource.",
19
+ docLink: `${DOCS_BASE}/401`,
20
+ commonCauses: [
21
+ "No Authorization header was sent",
22
+ "The bearer token expired",
23
+ "The session cookie was cleared"
24
+ ],
25
+ suggestion: "Confirm a valid `Authorization: Bearer <token>` header is sent and the token has not expired."
26
+ },
27
+ 403: {
28
+ status: 403,
29
+ title: "Forbidden",
30
+ message: "You do not have permission to access this resource.",
31
+ docLink: `${DOCS_BASE}/403`,
32
+ commonCauses: [
33
+ "The authenticated user lacks the required ability or role",
34
+ "A Gate or policy denied access (see app/Gates.ts)",
35
+ "The token was issued without the needed ability"
36
+ ],
37
+ suggestion: "Check Gates / policies and the abilities encoded in the access token."
38
+ },
39
+ 404: {
40
+ status: 404,
41
+ title: "Not Found",
42
+ message: "The requested resource could not be found.",
43
+ docLink: `${DOCS_BASE}/404`,
44
+ commonCauses: [
45
+ "The route is not registered in app/Routes.ts",
46
+ "A typo in the URL path",
47
+ "A model lookup returned no row (ModelNotFoundError)"
48
+ ],
49
+ suggestion: "Run `buddy route:list` to see registered routes, or verify the model exists with the given id."
50
+ },
51
+ 405: {
52
+ status: 405,
53
+ title: "Method Not Allowed",
54
+ message: "The request method is not supported for this resource.",
55
+ docLink: `${DOCS_BASE}/405`,
56
+ commonCauses: [
57
+ "The route is registered for a different HTTP method",
58
+ "A form posted GET when the route expects POST"
59
+ ],
60
+ suggestion: "Confirm the HTTP method in `app/Routes.ts` matches what the client sent."
61
+ },
62
+ 408: {
63
+ status: 408,
64
+ title: "Request Timeout",
65
+ message: "The request took too long to complete.",
66
+ docLink: `${DOCS_BASE}/408`,
67
+ commonCauses: [
68
+ "A long-running query or external API call exceeded the timeout",
69
+ "The client uploaded a slow body that stalled"
70
+ ],
71
+ suggestion: "Move slow work into a queued job, or raise the route timeout if the work is genuinely long."
72
+ },
73
+ 409: {
74
+ status: 409,
75
+ title: "Conflict",
76
+ message: "The request conflicts with the current state of the resource.",
77
+ docLink: `${DOCS_BASE}/409`,
78
+ commonCauses: [
79
+ "A unique-constraint violation (duplicate email, slug, etc.)",
80
+ "Optimistic locking detected a stale write"
81
+ ],
82
+ suggestion: "Re-fetch the resource and retry, or surface the conflict to the user."
83
+ },
84
+ 410: {
85
+ status: 410,
86
+ title: "Gone",
87
+ message: "The requested resource is no longer available.",
88
+ docLink: `${DOCS_BASE}/410`,
89
+ commonCauses: ["The resource was permanently deleted", "A signed URL expired"],
90
+ suggestion: "Issue a fresh signed URL or fall back to the canonical resource."
91
+ },
92
+ 422: {
93
+ status: 422,
94
+ title: "Unprocessable Entity",
95
+ message: "The request was well-formed but could not be processed.",
96
+ docLink: `${DOCS_BASE}/422`,
97
+ commonCauses: [
98
+ "Validation rules from the action / model rejected the payload",
99
+ "A field value is outside the allowed range or shape"
100
+ ],
101
+ suggestion: "Inspect `errors` in the response body \u2014 each key maps to a failing field."
102
+ },
103
+ 429: {
104
+ status: 429,
105
+ title: "Too Many Requests",
106
+ message: "You have exceeded the rate limit.",
107
+ docLink: `${DOCS_BASE}/429`,
108
+ commonCauses: ["Rate-limit middleware tripped on this IP / token", "A retry loop is hammering the endpoint"],
109
+ suggestion: "Honor the `Retry-After` response header and back off before retrying."
110
+ },
111
+ 500: {
112
+ status: 500,
113
+ title: "Internal Server Error",
114
+ message: "An unexpected error occurred on the server.",
115
+ docLink: `${DOCS_BASE}/500`,
116
+ commonCauses: [
117
+ "An unhandled exception in an action or middleware",
118
+ "A failing database connection or migration",
119
+ "A misconfigured environment variable"
120
+ ],
121
+ suggestion: "Check server logs for the original stack trace \u2014 the error page above shows the throw site in dev."
122
+ },
123
+ 502: {
124
+ status: 502,
125
+ title: "Bad Gateway",
126
+ message: "The server received an invalid response from an upstream server.",
127
+ docLink: `${DOCS_BASE}/502`,
128
+ commonCauses: ["An upstream HTTP API returned a malformed response", "A reverse proxy could not reach the origin"],
129
+ suggestion: "Verify the upstream service is healthy and returning the expected content type."
130
+ },
131
+ 503: {
132
+ status: 503,
133
+ title: "Service Unavailable",
134
+ message: "The service is temporarily unavailable.",
135
+ docLink: `${DOCS_BASE}/503`,
136
+ commonCauses: ["Maintenance mode is enabled", "A health check is failing", "A dependency (db, redis, queue) is down"],
137
+ suggestion: "Run `buddy doctor` and check dependent services."
138
+ },
139
+ 504: {
140
+ status: 504,
141
+ title: "Gateway Timeout",
142
+ message: "The upstream server did not respond in time.",
143
+ docLink: `${DOCS_BASE}/504`,
144
+ commonCauses: ["An upstream HTTP call exceeded its deadline", "A long-running database query timed out"],
145
+ suggestion: "Move the work to a queued job or raise the upstream timeout if the latency is expected."
146
+ }
147
+ };
148
+ import {
149
+ buildErrorMarkdown,
150
+ escapeHtml,
151
+ renderExceptionTrace,
152
+ wrapErrorPage
153
+ } from "./error-page-template";
154
+ import { ERROR_PAGE_CSS } from "./error-page-styles";
155
+
156
+ export { ERROR_PAGE_CSS };
157
+ const FRAMEWORK_FRAME_FRAGMENTS = [
158
+ "/storage/framework/core/",
159
+ "/node_modules/@stacksjs/",
160
+ "node:internal/",
161
+ "bun:wrap"
162
+ ];
163
+ export function isFrameworkFrame(file) {
164
+ if (!file)
165
+ return !1;
166
+ return FRAMEWORK_FRAME_FRAGMENTS.some((f) => file.includes(f));
167
+ }
168
+ function parseStackTrace(stack, basePaths, options = {}) {
169
+ if (!stack)
170
+ return [];
171
+ const lines = stack.split(`
172
+ `).slice(1), frames = [], includeAll = options.includeFrameworkFrames === !0;
173
+ for (const line of lines) {
174
+ const match = line.match(/^\s*at\s+(?:(.+?)\s+\()?(.+?):(\d+):(\d+)\)?$/);
175
+ if (match) {
176
+ let file = match[2];
177
+ if (file === void 0)
178
+ continue;
179
+ const original = file, isFramework = isFrameworkFrame(original);
180
+ if (basePaths) {
181
+ for (const basePath of basePaths)
182
+ if (file.startsWith(basePath)) {
183
+ file = file.slice(basePath.length + 1);
184
+ break;
185
+ }
186
+ }
187
+ if (!includeAll && isFramework)
188
+ continue;
189
+ frames.push({
190
+ function: match[1] || "<anonymous>",
191
+ file,
192
+ absoluteFile: original,
193
+ isFramework,
194
+ line: parseInt(match[3] ?? "0", 10),
195
+ column: parseInt(match[4] ?? "0", 10)
196
+ });
197
+ }
198
+ }
199
+ if (!includeAll && frames.length === 0)
200
+ return parseStackTrace(stack, basePaths, { includeFrameworkFrames: !0 });
201
+ return frames;
202
+ }
203
+ function loadCustomErrorPage(status, title, message) {
204
+ let resourcesPath;
205
+ try {
206
+ const mod = require("@stacksjs/path");
207
+ resourcesPath = mod.resourcesPath ?? mod.path?.resourcesPath;
208
+ } catch {}
209
+ if (!resourcesPath)
210
+ return null;
211
+ const fs = require("node:fs"), candidates = [
212
+ resourcesPath(`views/errors/${status}.html`),
213
+ resourcesPath("views/errors/error.html")
214
+ ];
215
+ for (const filePath of candidates)
216
+ try {
217
+ if (!fs.existsSync(filePath))
218
+ continue;
219
+ return fs.readFileSync(filePath, "utf-8").replace(/\{\{\s*status\s*\}\}/g, escapeHtml(String(status))).replace(/\{\{\s*title\s*\}\}/g, escapeHtml(title)).replace(/\{\{\s*message\s*\}\}/g, escapeHtml(message));
220
+ } catch {}
221
+ return null;
222
+ }
223
+ export function renderProductionErrorPage(status) {
224
+ const httpError = HTTP_ERRORS[status] || {
225
+ status,
226
+ title: "Error",
227
+ message: "An unexpected error occurred."
228
+ }, custom = loadCustomErrorPage(httpError.status, httpError.title, httpError.message);
229
+ if (custom !== null)
230
+ return custom;
231
+ return `<!DOCTYPE html>
232
+ <html lang="en">
233
+ <head>
234
+ <meta charset="UTF-8">
235
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
236
+ <title>${httpError.status} - ${httpError.title}</title>
237
+ <style>${ERROR_PAGE_CSS}</style>
238
+ </head>
239
+ <body>
240
+ <div class="production-page">
241
+ <div class="production-status">${httpError.status}</div>
242
+ <h1 class="production-title">${escapeHtml(httpError.title)}</h1>
243
+ <p class="production-message">${escapeHtml(httpError.message)}</p>
244
+ <a href="/" class="production-link">\u2190 Back to Home</a>
245
+ </div>
246
+ </body>
247
+ </html>`;
248
+ }
249
+ export function renderHttpErrorHints(status) {
250
+ const info = HTTP_ERRORS[status];
251
+ if (!info)
252
+ return "";
253
+ const hasCauses = Array.isArray(info.commonCauses) && info.commonCauses.length > 0, hasSuggestion = typeof info.suggestion === "string" && info.suggestion.length > 0, hasDoc = typeof info.docLink === "string" && info.docLink.length > 0;
254
+ if (!hasCauses && !hasSuggestion && !hasDoc)
255
+ return "";
256
+ const causes = hasCauses ? `<ul class="error-hint-causes">${info.commonCauses.map((c) => `<li>${escapeHtml(c)}</li>`).join("")}</ul>` : "", suggestion = hasSuggestion ? `<p class="error-hint-suggestion">${escapeHtml(info.suggestion)}</p>` : "", doc = hasDoc ? `<a class="text-blue-600 text-sm dark:text-blue-500 hover:underline" href="${escapeHtml(info.docLink)}" target="_blank" rel="noreferrer noopener">Read the docs \u2192</a>` : "";
257
+ return `<section class="p-4 bg-amber-200/30 dark:bg-amber-950/40 border border-amber-200 rounded-xl dark:border-amber-800 shadow-xs">
258
+ <div class="mb-2 font-semibold text-amber-900 text-sm dark:text-amber-300">Likely causes &amp; next steps</div>
259
+ <div class="text-neutral-700 text-sm dark:text-neutral-300">${causes}${suggestion}${doc}</div>
260
+ </section>`;
261
+ }
262
+
263
+ export class ErrorPageHandler {
264
+ config;
265
+ framework;
266
+ request;
267
+ routing;
268
+ user;
269
+ queries = [];
270
+ constructor(config) {
271
+ this.config = {
272
+ appName: "App",
273
+ theme: "auto",
274
+ showEnvironment: !0,
275
+ showQueries: !0,
276
+ showRequest: !0,
277
+ enableCopyMarkdown: !0,
278
+ snippetLines: 8,
279
+ ...config
280
+ };
281
+ }
282
+ setFramework(name, version) {
283
+ this.framework = { name, version };
284
+ return this;
285
+ }
286
+ setRequest(request) {
287
+ if (request instanceof Request) {
288
+ const url = new URL(request.url);
289
+ this.request = {
290
+ method: request.method,
291
+ url: request.url,
292
+ headers: Object.fromEntries(request.headers.entries()),
293
+ queryParams: Object.fromEntries(url.searchParams.entries())
294
+ };
295
+ } else
296
+ this.request = request;
297
+ return this;
298
+ }
299
+ setRouting(routing) {
300
+ this.routing = routing;
301
+ return this;
302
+ }
303
+ setUser(user) {
304
+ this.user = user;
305
+ return this;
306
+ }
307
+ addQuery(query, time, connection) {
308
+ this.queries.push({ query, time, connection });
309
+ return this;
310
+ }
311
+ async render(error, status = 500) {
312
+ try {
313
+ const { renderDevErrorPage } = await import("./error-page-renderer");
314
+ return await renderDevErrorPage({
315
+ error,
316
+ status,
317
+ config: this.config,
318
+ framework: this.framework,
319
+ request: this.request,
320
+ routing: this.routing,
321
+ user: this.user,
322
+ queries: this.queries
323
+ });
324
+ } catch (renderError) {
325
+ console.error("[ErrorPageHandler] STX render failed, using fallback:", renderError);
326
+ return this.renderFallback(error, status);
327
+ }
328
+ }
329
+ renderFallback(error, status) {
330
+ const frames = parseStackTrace(error.stack, this.config.basePaths, {
331
+ includeFrameworkFrames: this.config.showFrameworkFrames === !0
332
+ }), statusTitle = HTTP_ERRORS[status]?.title ?? "Error", topFrame = frames[0], body = `
333
+ <header class="header"><div class="header-title"><span class="header-dot"></span><span>${escapeHtml(statusTitle)}</span></div></header>
334
+ <section class="summary">
335
+ <h1>${escapeHtml(error.name || "Error")}</h1>
336
+ ${topFrame ? `<div class="summary-file">${escapeHtml(topFrame.file)}:${topFrame.line}</div>` : ""}
337
+ <p class="summary-message">${escapeHtml(error.message)}</p>
338
+ </section>
339
+ ${renderHttpErrorHints(status)}
340
+ ${renderExceptionTrace(frames, this.config.snippetLines ?? 8)}
341
+ `, markdown = buildErrorMarkdown({
342
+ statusTitle,
343
+ errorName: error.name || "Error",
344
+ errorMessage: error.message,
345
+ status,
346
+ file: topFrame?.file,
347
+ line: topFrame?.line,
348
+ request: this.request,
349
+ framework: this.framework,
350
+ frames
351
+ });
352
+ return wrapErrorPage(body, markdown);
353
+ }
354
+ async handleError(error, status = 500) {
355
+ const html = await this.render(error, status);
356
+ return new Response(html, {
357
+ status,
358
+ headers: { "Content-Type": "text/html; charset=utf-8" }
359
+ });
360
+ }
361
+ }
362
+ export function createErrorHandler(config) {
363
+ return new ErrorPageHandler(config);
364
+ }
365
+ export async function renderErrorPage(error, status = 500, config) {
366
+ return createErrorHandler(config).render(error, status);
367
+ }
368
+ export async function renderError(error, status = 500) {
369
+ return renderErrorPage(error, status);
370
+ }
371
+ export async function errorResponse(error, status = 500, config) {
372
+ return createErrorHandler(config).handleError(error, status);
373
+ }
@@ -0,0 +1,108 @@
1
+ import fs from "node:fs";
2
+ import { dirname } from "node:path";
3
+ import * as process from "node:process";
4
+ function italic(str) {
5
+ return `\x1B[3m${str}\x1B[23m`;
6
+ }
7
+ function stripAnsi(str) {
8
+ return str.replace(/\x1B\[[0-9;]*m/g, "");
9
+ }
10
+ import * as path from "@stacksjs/path";
11
+ import { ExitCode } from "@stacksjs/types";
12
+
13
+ export class ErrorHandler {
14
+ static isTestEnvironment = !1;
15
+ static shouldExitProcess = !1;
16
+ static handle(err, options) {
17
+ if (!this.isTestEnvironment)
18
+ this.shouldExitProcess = options?.shouldExit === !0;
19
+ if (options?.silent !== !0)
20
+ this.writeErrorToConsole(err);
21
+ let errorMessage;
22
+ if (options?.message)
23
+ errorMessage = options.message;
24
+ else if (err instanceof Error)
25
+ errorMessage = err.message;
26
+ else if (typeof err === "string")
27
+ errorMessage = err;
28
+ else
29
+ errorMessage = JSON.stringify(err);
30
+ const error = Error(errorMessage);
31
+ if (err instanceof Error)
32
+ Object.assign(error, err);
33
+ this.writeErrorToFile(error).catch((e) => console.error(e));
34
+ return error;
35
+ }
36
+ static handleError(err, options) {
37
+ this.handle(err, options);
38
+ return err;
39
+ }
40
+ static async writeErrorToFile(err, context) {
41
+ if (!(err instanceof Error)) {
42
+ console.error("Error is not an instance of Error:", err);
43
+ return;
44
+ }
45
+ const contextStr = context ? ` | url=${context.url || "N/A"} method=${context.method || "N/A"} user=${context.userId || "anonymous"}` : "", stackLine = err.stack ? `
46
+ ${err.stack.split(`
47
+ `).slice(1, 4).join(`
48
+ `)}` : "", formattedError = `[${new Date().toISOString()}] ${err.name}: ${err.message}${contextStr}${stackLine}
49
+ `, logFilePath = path.logsPath("stacks.log") ?? path.logsPath("errors.log");
50
+ try {
51
+ await fs.promises.mkdir(path.dirname(logFilePath), { recursive: !0 });
52
+ await fs.promises.appendFile(logFilePath, formattedError);
53
+ } catch (error) {
54
+ console.error("Failed to write to error file:", error);
55
+ }
56
+ }
57
+ static writeErrorToConsole(err) {
58
+ let errorString;
59
+ if (err instanceof Error)
60
+ errorString = err.message;
61
+ else if (typeof err === "string")
62
+ errorString = err;
63
+ else
64
+ errorString = JSON.stringify(err);
65
+ console.error(errorString);
66
+ if (errorString.includes("bunx --bun cdk destroy") || errorString === `Failed to execute command: ${italic("bunx --bun eslint . --fix")}` || errorString === `Failed to execute command: ${italic("bun storage/framework/core/actions/src/lint/fix.ts")}`) {
67
+ if (!this.isTestEnvironment) {
68
+ console.log("No need to worry. The edge function is currently being destroyed. Please run `buddy undeploy` shortly again, and continue doing so until it succeeds running.");
69
+ console.log("Hoping to see you back soon!");
70
+ }
71
+ }
72
+ if (this.shouldExitProcess)
73
+ process.exit(ExitCode.FatalError);
74
+ }
75
+ }
76
+ let defaultLogPath = "storage/logs/stacks.log";
77
+ export function setLogPath(path) {
78
+ defaultLogPath = path;
79
+ }
80
+ export async function writeToLogFile(message, options) {
81
+ const formattedMessage = `[${new Date().toISOString()}] ${message}
82
+ `, logFile = options?.logFile ?? defaultLogPath, dirPath = dirname(logFile);
83
+ await fs.promises.mkdir(dirPath, { recursive: !0 });
84
+ await fs.promises.appendFile(logFile, formattedMessage);
85
+ }
86
+ export function handleError(err, options) {
87
+ let errorMessage, contextData;
88
+ if (options && typeof options === "object" && !("shouldExit" in options) && !("silent" in options) && !("message" in options)) {
89
+ contextData = options;
90
+ options = void 0;
91
+ }
92
+ const errMsg = err instanceof Error ? err.message : typeof err === "string" ? err : JSON.stringify(err);
93
+ if (options && "message" in options)
94
+ errorMessage = `${errMsg}: ${options.message}`;
95
+ else
96
+ errorMessage = errMsg;
97
+ let logMessage = `ERROR: ${stripAnsi(errorMessage)}`;
98
+ if (contextData)
99
+ logMessage += `
100
+ Context: ${JSON.stringify(contextData, null, 2)}`;
101
+ writeToLogFile(logMessage).catch((err) => {
102
+ console.error("Failed to write error log:", err);
103
+ });
104
+ const error = Error(errorMessage);
105
+ if (err instanceof Error)
106
+ Object.assign(error, err);
107
+ return ErrorHandler.handle(error, { ...options, message: errorMessage });
108
+ }
package/dist/http.js ADDED
@@ -0,0 +1,165 @@
1
+ import {
2
+ createErrorHandler,
3
+ HTTP_ERRORS,
4
+ renderProductionErrorPage
5
+ } from "./error-page";
6
+
7
+ export class HttpError extends Error {
8
+ status;
9
+ details;
10
+ constructor(status, message, details) {
11
+ super(message);
12
+ this.status = status;
13
+ this.name = httpStatusName(status);
14
+ if (details !== void 0)
15
+ this.details = details;
16
+ }
17
+ }
18
+ function httpStatusName(status) {
19
+ switch (status) {
20
+ case 400:
21
+ return "Bad Request";
22
+ case 401:
23
+ return "Unauthorized";
24
+ case 402:
25
+ return "Payment Required";
26
+ case 403:
27
+ return "Forbidden";
28
+ case 404:
29
+ return "Not Found";
30
+ case 405:
31
+ return "Method Not Allowed";
32
+ case 408:
33
+ return "Request Timeout";
34
+ case 409:
35
+ return "Conflict";
36
+ case 410:
37
+ return "Gone";
38
+ case 413:
39
+ return "Payload Too Large";
40
+ case 415:
41
+ return "Unsupported Media Type";
42
+ case 422:
43
+ return "Unprocessable Entity";
44
+ case 423:
45
+ return "Locked";
46
+ case 425:
47
+ return "Too Early";
48
+ case 426:
49
+ return "Upgrade Required";
50
+ case 428:
51
+ return "Precondition Required";
52
+ case 429:
53
+ return "Too Many Requests";
54
+ case 431:
55
+ return "Request Header Fields Too Large";
56
+ case 451:
57
+ return "Unavailable For Legal Reasons";
58
+ case 500:
59
+ return "Internal Server Error";
60
+ case 501:
61
+ return "Not Implemented";
62
+ case 502:
63
+ return "Bad Gateway";
64
+ case 503:
65
+ return "Service Unavailable";
66
+ case 504:
67
+ return "Gateway Timeout";
68
+ case 507:
69
+ return "Insufficient Storage";
70
+ case 508:
71
+ return "Loop Detected";
72
+ case 511:
73
+ return "Network Authentication Required";
74
+ default:
75
+ return status >= 400 && status < 500 ? "Client Error" : "Server Error";
76
+ }
77
+ }
78
+
79
+ export class HttpErrorHandler {
80
+ handler = createErrorHandler();
81
+ isDevelopment;
82
+ constructor(options) {
83
+ this.isDevelopment = options?.isDevelopment ?? !0;
84
+ if (options?.config)
85
+ this.handler = createErrorHandler(options.config);
86
+ this.handler.setFramework("Stacks");
87
+ }
88
+ setRequest(request) {
89
+ this.handler.setRequest(request);
90
+ return this;
91
+ }
92
+ setRouting(routing) {
93
+ this.handler.setRouting(routing);
94
+ return this;
95
+ }
96
+ addQuery(query, time, connection) {
97
+ this.handler.addQuery(query, time, connection);
98
+ return this;
99
+ }
100
+ async handle(error, status = 500) {
101
+ if (this.isDevelopment)
102
+ return this.handler.handleError(error, status);
103
+ return new Response(renderProductionErrorPage(status), {
104
+ status,
105
+ headers: { "Content-Type": "text/html; charset=utf-8" }
106
+ });
107
+ }
108
+ notFound(message) {
109
+ const error = new HttpError(404, message || "The requested resource could not be found.");
110
+ return this.handle(error, 404);
111
+ }
112
+ serverError(error) {
113
+ return this.handle(error, 500);
114
+ }
115
+ forbidden(message) {
116
+ const error = new HttpError(403, message || "You do not have permission to access this resource.");
117
+ return this.handle(error, 403);
118
+ }
119
+ unauthorized(message) {
120
+ const error = new HttpError(401, message || "Authentication is required to access this resource.");
121
+ return this.handle(error, 401);
122
+ }
123
+ badRequest(message) {
124
+ const error = new HttpError(400, message || "The request was malformed or invalid.");
125
+ return this.handle(error, 400);
126
+ }
127
+ validationError(message) {
128
+ const error = new HttpError(422, message || "The request was well-formed but could not be processed.");
129
+ return this.handle(error, 422);
130
+ }
131
+ tooManyRequests(message) {
132
+ const error = new HttpError(429, message || "You have exceeded the rate limit.");
133
+ return this.handle(error, 429);
134
+ }
135
+ serviceUnavailable(message) {
136
+ const error = new HttpError(503, message || "The service is temporarily unavailable.");
137
+ return this.handle(error, 503);
138
+ }
139
+ }
140
+ export function createHttpErrorHandler(options) {
141
+ return new HttpErrorHandler(options);
142
+ }
143
+ export async function renderHttpError(error, request, options) {
144
+ const handler = createHttpErrorHandler({
145
+ isDevelopment: options?.isDevelopment,
146
+ config: options?.config
147
+ });
148
+ if (request)
149
+ handler.setRequest(request);
150
+ return handler.handle(error, options?.status);
151
+ }
152
+ export function errorMiddleware(options) {
153
+ const handler = createHttpErrorHandler(options);
154
+ return async (error, request) => {
155
+ handler.setRequest(request);
156
+ let status = 500;
157
+ if (error instanceof HttpError)
158
+ status = error.status;
159
+ else if ("status" in error && typeof error.status === "number")
160
+ status = error.status;
161
+ else if ("statusCode" in error && typeof error.statusCode === "number")
162
+ status = error.statusCode;
163
+ return handler.handle(error, status);
164
+ };
165
+ }