Return 400 for malformed testimonial JSON#454
Conversation
Greptile SummaryThis PR adds a targeted fix to
Confidence Score: 4/5The change is minimal and confined to a single error-handling path; the happy path and all existing validations are untouched. The bare catch block will also intercept non-parse exceptions from request.json() and return 400 instead of letting them bubble to the outer 500 handler. In practice this is unlikely, but narrowing to SyntaxError would make the intent explicit. The inner try/catch in route.ts (lines 74–78) is the only spot worth a second look. Important Files Changed
Sequence DiagramsequenceDiagram
participant Client
participant Route as POST /api/testimonials
participant Auth as getAuthContext
participant Parser as request.json
participant DB as createServiceClient
Client->>Route: POST with body
Route->>Auth: check auth
Auth-->>Route: auth context or null
alt unauthenticated
Route-->>Client: 401 Unauthorized
else malformed JSON (new path)
Route->>Parser: parse body
Parser-->>Route: throws SyntaxError
Route-->>Client: 400 Invalid JSON body
else valid JSON
Route->>Parser: parse body
Parser-->>Route: body object
Route->>DB: validate and insert testimonial
DB-->>Route: result
Route-->>Client: 201 testimonial
end
Reviews (1): Last reviewed commit: "Handle malformed testimonial JSON" | Re-trigger Greptile |
| try { | ||
| body = await request.json(); | ||
| } catch { | ||
| return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 }); | ||
| } |
There was a problem hiding this comment.
The bare
catch swallows every exception thrown by request.json(), not only SyntaxError. In nearly all real cases request.json() only throws SyntaxError, but if a stream or body-reader error surfaces here it will be reported to the caller as 400 Invalid JSON body rather than bubbling to the outer catch and returning a 500. Narrowing to SyntaxError keeps the semantics accurate and lets unexpected errors reach the generic handler.
| try { | |
| body = await request.json(); | |
| } catch { | |
| return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 }); | |
| } | |
| try { | |
| body = await request.json(); | |
| } catch (err) { | |
| if (err instanceof SyntaxError) { | |
| return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 }); | |
| } | |
| throw err; | |
| } |
|
CI is green for PR #454. Verification:
uGig invoice evidence has been sent for this PR. |
Fixes #453.
Summary
POST /api/testimonialsreceives malformed JSONVerification
vitest run src/app/api/testimonials/route.test.tstsc --noEmit