diff options
| author | Mohamed Bassem <me@mbassem.com> | 2024-10-20 14:51:33 +0000 |
|---|---|---|
| committer | Mohamed Bassem <me@mbassem.com> | 2024-10-20 14:51:33 +0000 |
| commit | f5fd3c48b7f3de18bcacd584c8d816250fbcad19 (patch) | |
| tree | 3179e6293672932b254ff269608184956ac82879 /apps | |
| parent | 719e25d8254fd9ab2516f5faf6d2f07af4257792 (diff) | |
| download | karakeep-f5fd3c48b7f3de18bcacd584c8d816250fbcad19.tar.zst | |
fix: Better handling for body JSON parsing errors
Diffstat (limited to 'apps')
| -rw-r--r-- | apps/web/app/api/v1/utils/handler.ts | 23 |
1 files changed, 22 insertions, 1 deletions
diff --git a/apps/web/app/api/v1/utils/handler.ts b/apps/web/app/api/v1/utils/handler.ts index d5f470df..84847d71 100644 --- a/apps/web/app/api/v1/utils/handler.ts +++ b/apps/web/app/api/v1/utils/handler.ts @@ -98,7 +98,24 @@ export async function buildHandler< let body: SchemaType<BodyT> | undefined = undefined; if (bodySchema) { - body = bodySchema.parse(await req.json()) as SchemaType<BodyT>; + if (req.headers.get("Content-Type") !== "application/json") { + throw new TRPCError({ + code: "BAD_REQUEST", + message: "Content-Type must be application/json", + }); + } + + let bodyJson = undefined; + try { + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + bodyJson = await req.json(); + } catch (e) { + throw new TRPCError({ + code: "BAD_REQUEST", + message: `Invalid JSON: ${(e as Error).message}`, + }); + } + body = bodySchema.parse(bodyJson) as SchemaType<BodyT>; } const { status, resp } = await handler({ @@ -138,6 +155,10 @@ export async function buildHandler< }, }); } else { + const error = e as Error; + console.error( + `Unexpected error in: ${req.method} ${req.nextUrl.pathname}:\n${error.stack}`, + ); return new Response(JSON.stringify({ code: "UnknownError" }), { status: 500, headers: { |
