fix(validate): convert malformed JSON to 400 in validated-handler path#1465
Conversation
A rejected `req.json()` in the validated-request proxy surfaced as an unhandled 500. Wrap the parse so a malformed JSON body becomes a 400 "Invalid JSON body", consistent with `readBody`. Co-Authored-By: Claude Fable 5 <[email protected]>
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
pi0x
left a comment
There was a problem hiding this comment.
Independent review — LGTM (posting as comment since GitHub blocks self-approval on this account).
Clean, minimal fix that closes a real gap: a malformed JSON body to a defineValidatedHandler previously surfaced as an unhandled 500, now a 400.
Verified locally on the branch:
- Error shape is byte-for-byte consistent with
readBody(src/utils/body.ts):status: 400,statusText: "Bad Request",message: "Invalid JSON body". - The
.catch()sits only onreq.json(), before the validation.then()chain, so schema/validation errors are untouched and keep their existingcreateValidationErrorshape/status. - The regression test genuinely fails without the fix (asserted 500 before, 400 after) and passes with it. It correctly satisfies header/query validation first so the JSON-parse path is actually exercised.
pnpm vitest run test/handler.test.tsandpnpm lintboth green.
Two minor, non-blocking notes (both edge cases and strict improvements over the prior 500):
req.json()bundles body-reading + parsing, so a genuine body/stream read error would also be reported as 400 "Invalid JSON body".readBodywraps onlyJSON.parse(notreq.text()), so it would surface such a read error as 500. Rare, but a slight semantic divergence if you want the two paths to treat internal read failures identically.- Empty body now returns 400 "Invalid JSON body" here, whereas
readBodytreats an empty body asundefinedand hands it to the schema. Not wrong, just worth being aware the two paths diverge for empty bodies.
Neither blocks merge.
🤖 Generated with Claude Code
|
Caution Review failedAn error occurred during the review process. Please try again later. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
A rejected
req.json()in the validated-request proxy (_validatedJson) was not caught, so a malformed JSON body sent to adefineValidatedHandlersurfaced as an unhandled 500 — inconsistent withreadBody, which returns a 400 "Invalid JSON body".This wraps the
.json()call so a parse failure becomes a400HTTPErrorwith message "Invalid JSON body". Adds a regression test covering malformed JSON to a validated handler.🤖 Generated with Claude Code