-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathnetworking.ts
56 lines (48 loc) · 1.51 KB
/
networking.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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import type { ZodSchema } from "zod";
import { HTTPException } from "hono/http-exception";
import { ContentfulStatusCode } from "hono/utils/http-status";
import { resolver } from "hono-openapi/zod";
import { CancellationError } from "@/common/errors.ts";
import { logger } from "@/common/logging.ts";
// Originally from Stoker adopted for hono-openapi
export const jsonContent = <T extends ZodSchema>(
schema: T,
description: string,
) => {
return {
content: {
"application/json": {
schema: resolver(schema),
},
},
description,
};
};
// Return an HTTP exception for static request errors
export function toHttpException(error: unknown, status = 422) {
let message = "An unexpected error occurred";
if (error instanceof CancellationError) {
status = 408;
message = error.message;
} else if (error instanceof Error) {
message = error.message;
}
const statusCode = status as ContentfulStatusCode;
throw new HTTPException(statusCode, { message });
}
// Return an error payload for stream generators
export function toGeneratorError(error: unknown) {
let message = "An unexpected error occurred";
if (error instanceof CancellationError) {
logger.error(error.message);
message = error.message;
} else if (error instanceof Error) {
logger.error(error.stack || error.message);
message = error.message;
}
return {
error: {
message,
},
};
}