Skip to content

Commit

Permalink
fix: Better handling for body JSON parsing errors
Browse files Browse the repository at this point in the history
  • Loading branch information
MohamedBassem committed Oct 20, 2024
1 parent 719e25d commit f5fd3c4
Showing 1 changed file with 22 additions and 1 deletion.
23 changes: 22 additions & 1 deletion apps/web/app/api/v1/utils/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down Expand Up @@ -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: {
Expand Down

0 comments on commit f5fd3c4

Please sign in to comment.