From f5fd3c48b7f3de18bcacd584c8d816250fbcad19 Mon Sep 17 00:00:00 2001 From: Mohamed Bassem Date: Sun, 20 Oct 2024 14:51:33 +0000 Subject: fix: Better handling for body JSON parsing errors --- apps/web/app/api/v1/utils/handler.ts | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) (limited to 'apps') 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 | undefined = undefined; if (bodySchema) { - body = bodySchema.parse(await req.json()) as SchemaType; + 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; } 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: { -- cgit v1.2.3-70-g09d2