-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.ts
29 lines (23 loc) · 933 Bytes
/
utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import { ZodError } from "zod";
import type { Context } from "hono";
import type { ApiErrorSchema } from "./types/zod.gen.js";
import { logger } from "./logger.js";
import * as prometheus from "./prometheus.js";
export function APIErrorResponse(ctx: Context, status: ApiErrorSchema["status"], code: ApiErrorSchema["code"], err: unknown) {
let message = "An unexpected error occured";
if (typeof err === "string") {
message = err;
} else if (err instanceof ZodError) {
message = err.issues.map(issue => `[${issue.code}] ${issue.path.join('/')}: ${issue.message}`).join('\n');
} else if (err instanceof Error) {
message = err.message;
}
const api_error = {
status,
code,
message
};
logger.error(api_error);
prometheus.request_error.inc({ pathname: ctx.req.path, status });
return ctx.json<ApiErrorSchema, typeof status>(api_error, status);
}