Skip to content

fix(validation): correct 'on' and 'property' fields in validation errors for constraint violations#1674

Open
raunak-rpm wants to merge 3 commits intoelysiajs:mainfrom
raunak-rpm:fix/validation-error-fields-1660
Open

fix(validation): correct 'on' and 'property' fields in validation errors for constraint violations#1674
raunak-rpm wants to merge 3 commits intoelysiajs:mainfrom
raunak-rpm:fix/validation-error-fields-1660

Conversation

@raunak-rpm
Copy link

@raunak-rpm raunak-rpm commented Jan 14, 2026

Summary

Fixes #1660 - Incorrect query validation error fields

Problem

When query validation fails due to constraint violations (like maximum: 100 with value 200), the validation error incorrectly returns:

  • on: "property" instead of on: "query"
  • property: "root" instead of property: "/limit"

Before (broken):

{
  "type": "validation",
  "on": "property",
  "property": "root",
  "message": "Expected number to be less or equal to 100"
}

After (fixed):

{
  "type": "validation",
  "on": "query",
  "property": "/limit",
  "message": "Expected number to be less or equal to 100"
}

Root Cause

When t.Numeric (or other Transform types) decode a value, they validate constraints inside the Decode step. If constraints fail, they throw a ValidationError with hardcoded type: 'property' from the internal type-system utilities (src/type-system/utils.ts:48).

This error is wrapped in TransformDecodeError, which Elysia's coerceTransformDecodeError function caught and re-threw directly via throw error.error, preserving the incorrect type.

The key insight is that TransformDecodeError.path has the correct path (e.g., /limit), but the inner ValidationError.valueError.path is empty because it was created against the inner schema (the Number), not the full Object schema.

Solution

Modified coerceTransformDecodeError in src/compose.ts to:

  1. Check if error.error?.valueError exists (indicating it's a ValidationError with constraint info)
  2. Extract the valueError and fix its path using TransformDecodeError.path
  3. Create a new ValidationError with the correct type context (e.g., 'query') and fixed errors
  4. Preserve existing behavior for non-ValidationError errors (e.g., NotFoundError thrown in Transform)

Testing

  • Added 2 new test cases for constraint violation error metadata
  • All 1448 tests pass (including existing "handle error in Transform" test)
  • Manually verified with reproduction case from issue

Reproduction

import { Elysia, t } from "elysia";

const app = new Elysia()
  .get("/", ({ query }) => query, {
    query: t.Object({
      limit: t.Number({ minimum: 1, maximum: 100, default: 10 }),
    }),
  })
  .listen(3000);

// Visit: http://localhost:3000?limit=200
// Now correctly returns: on: "query", property: "/limit"

Summary by CodeRabbit

  • Bug Fixes

    • Improved validation error handling so API responses include accurate constraint details and preserve precise error paths; non-validation errors continue to propagate as before.
  • Tests

    • Added tests covering constraint-violation metadata (min/max), nested object-path validation, and verification that response error details (type, location, property, message) are reported correctly.

✏️ Tip: You can customize this high-level summary in your review settings.

…ors for constraint violations

Fixes elysiajs#1660

## Problem
When query validation fails due to constraint violations (like
with value ), the validation error incorrectly returns:
- `on: 'property'` instead of `on: 'query'`
- `property: 'root'` instead of `property: '/limit'`

Type errors (like passing a non-numeric string) worked correctly.

## Root Cause
When `t.Numeric` (or other Transform types) decode a value, they validate
constraints inside the Decode step. If constraints fail, they throw a
`ValidationError` with hardcoded `type: 'property'` from the internal
type-system utilities.

This error is wrapped in `TransformDecodeError`, which Elysia's
`coerceTransformDecodeError` function caught and re-threw directly via
`throw error.error`, preserving the incorrect type.

## Solution
Modified `coerceTransformDecodeError` to:
1. Extract the `valueError` from the internal `ValidationError`
2. Fix the path using `TransformDecodeError.path` (which has the correct path)
3. Create a new `ValidationError` with the correct type context (e.g., 'query')
4. Preserve existing behavior for non-ValidationError errors (e.g., NotFoundError)

## Testing
- Added 2 new test cases for constraint violation error metadata
- All 1448 tests pass
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 14, 2026

Walkthrough

Adjusts transform-decode error handling to preserve and correct inner ValidationError paths for value-level constraint violations and adds tests verifying accurate on and property metadata for simple and nested query constraint errors.

Changes

Cohort / File(s) Summary
Error path correction
src/compose.ts
Add handling in coerceTransformDecodeError for TransformDecodeError whose error.error is a ValidationError with a valueError: extract the inner valueError, set its path from the outer error, aggregate into errs (including a First reference), and throw a reconstructed ValidationError. Non-Validation inner errors are rethrown or handled by existing logic.
Constraint violation tests
test/validator/query.test.ts
Append two tests: one for numeric query parameter constraints (min/max and subsequent type error) and one for nested object constraint violations, asserting 422 responses and correct type, on, property, and message fields.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 I nudged the paths that lost their way,
Pulled inner errors back to where they stay.
Constraints now point, no more disguise,
Queries bloom with clearer eyes.
🥕✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically describes the main fix: correcting 'on' and 'property' fields in validation errors for constraint violations, which is the primary change in this PR.
Linked Issues check ✅ Passed The PR fully addresses issue #1660 by fixing the coerceTransformDecodeError function to correctly set 'on' and 'property' fields in constraint-violation errors, with test coverage and verified reproduction.
Out of Scope Changes check ✅ Passed All changes are directly scoped to fixing the validation error fields issue: the compose.ts fix for error handling and test.ts additions for validation of the fix.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings


📜 Recent review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 03cfb4a and a1b78a7.

📒 Files selected for processing (1)
  • src/compose.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/compose.ts

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.


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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@pkg-pr-new
Copy link

pkg-pr-new bot commented Jan 14, 2026

Open in StackBlitz

npm i https://pkg.pr.new/elysiajs/elysia@1674

commit: a1b78a7

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/compose.ts (1)

452-476: Don’t pre-set c.set.status=422 if you might rethrow error.error (status can become wrong/sticky).

Right now, any TransformDecodeError sets 422 (Line 464) even if you then rethrow error.error (Line 475). Because later error handling often won’t overwrite an already-4xx status, a non-validation error rethrown here (your comment mentions NotFoundError) can incorrectly end up as a 422 response.

Proposed fix (only set 422 when throwing a ValidationError)
 const coerceTransformDecodeError = (
   fnLiteral: string,
   type: string,
   allowUnsafeValidationDetails = false,
   value = `c.${type}`
 ) =>
   // NOTE: We only handle TransformDecodeError and intentionally let other errors
   // fall through silently. This is required because TypeBox's Transform mechanism
   // throws internal errors during successful decode operations that are not
   // TransformDecodeError. Re-throwing those would break Transform-based validation.
   `try{${fnLiteral}}catch(error){` +
   `if(error.constructor.name === 'TransformDecodeError'){` +
-  `c.set.status=422\n` +
   // Fix `#1660`: When error.error is a ValidationError with wrong 'type' field,
   // extract valueError and fix its path using TransformDecodeError.path
-  `if(error.error?.valueError){` +
+  `if(error.error?.valueError){` +
+  `c.set.status=422\n` +
   `const ve=error.error.valueError;` +
   `const fe={...ve,path:error.path};` +
   `const errs={[Symbol.iterator]:function*(){yield fe},First:()=>fe};` +
   `throw new ValidationError('${type}',validator.${type},${value},${allowUnsafeValidationDetails},errs)` +
   `}` +
   // If error.error exists but is not a ValidationError (e.g., NotFoundError),
   // re-throw it directly. Otherwise, create new ValidationError.
-  `throw error.error ?? new ValidationError('${type}',validator.${type},${value},${allowUnsafeValidationDetails})}` +
+  `if(error.error)throw error.error\n` +
+  `c.set.status=422\n` +
+  `throw new ValidationError('${type}',validator.${type},${value},${allowUnsafeValidationDetails})}` +
   `}`
🤖 Fix all issues with AI agents
In `@src/compose.ts`:
- Around line 465-472: Replace the duck-typed check `if
(error.error?.valueError)` with an explicit ValidationError type check—e.g., `if
(error.error instanceof ValidationError && error.error.valueError)`—so you only
treat true ValidationError instances (referencing the `error`,
`ValidationError`, and `valueError` symbols); keep the custom `errs` object and
its iterator/First contract as-is so `ValidationError` can call `errors.First()`
and revalidate via `validator.Errors()`; ensure you still construct `fe` using
`error.error.valueError` and `path: error.path` and throw the new
`ValidationError('${type}', validator.${type}, ${value},
${allowUnsafeValidationDetails}, errs)` as before.
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9fa92b5 and 5b5c817.

📒 Files selected for processing (1)
  • src/compose.ts

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.

@raunak-rpm raunak-rpm force-pushed the fix/validation-error-fields-1660 branch from 5b5c817 to 9fa92b5 Compare January 14, 2026 19:48
aunak added 2 commits January 15, 2026 15:09
Replace duck-typed check `if(error.error?.valueError)` with explicit
type check `if(error.error instanceof ValidationError && error.error.valueError)`
to ensure only true ValidationError instances are handled.
The instanceof check doesn't work in generated code strings because
ValidationError is not in scope at runtime. Using constructor.name
matches the existing pattern used for TransformDecodeError check.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Incorrect query validation error fields

2 participants