Skip to content

fix: (types) allow FastifySchemaValidationError[] as an error#6326

Merged
mcollina merged 1 commit intomainfrom
add-type-for-schema-val-errors
Sep 22, 2025
Merged

fix: (types) allow FastifySchemaValidationError[] as an error#6326
mcollina merged 1 commit intomainfrom
add-type-for-schema-val-errors

Conversation

@gurgunday
Copy link
Member

@gurgunday gurgunday commented Sep 21, 2025

This PR adds the FastifySchemaValidationError[] type to the error property of FastifyValidationResult that the code at runtime handles but is invisible:

fastify/lib/validation.js

Lines 241 to 255 in 9a67d3a

function wrapValidationError (result, dataVar, schemaErrorFormatter) {
if (result instanceof Error) {
result.statusCode = result.statusCode || 400
result.code = result.code || 'FST_ERR_VALIDATION'
result.validationContext = result.validationContext || dataVar
return result
}
const error = schemaErrorFormatter(result, dataVar)
error.statusCode = error.statusCode || 400
error.code = error.code || 'FST_ERR_VALIDATION'
error.validation = result
error.validationContext = dataVar
return error
}

The code above calls schemaErrorFormatter if the property is not an error object, which by default handles an array of FastifySchemaValidationError objects:

fastify/lib/context.js

Lines 84 to 93 in 9a67d3a

function defaultSchemaErrorFormatter (errors, dataVar) {
let text = ''
const separator = ', '
for (let i = 0; i !== errors.length; ++i) {
const e = errors[i]
text += dataVar + (e.instancePath || '') + ' ' + e.message + separator
}
return new Error(text.slice(0, -separator.length))
}

Not having this type causes Type Providers in the ecosystem to assert the type incorrectly:

https://github.com/fastify/fastify-type-provider-typebox/blob/2c8319e69070482b83bb527c9ae8fe7fcbcc4d94/index.mts#L26

https://github.com/fastify/fastify-type-provider-typebox/pull/243/files#diff-382414b6b7a87c32132ad230c522280fe2a6d4efdaf7e32cc5ef3917dbb0404dR35

https://github.com/turkerdev/fastify-type-provider-zod/blob/4e658779dbc788356b9b9e3c67fea6d17aca801e/src/core.ts#L187-L189

Copy link
Member

@mcollina mcollina left a comment

Choose a reason for hiding this comment

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

lgtm

@mcollina mcollina merged commit 80ef70c into main Sep 22, 2025
36 checks passed
@mcollina mcollina deleted the add-type-for-schema-val-errors branch September 22, 2025 12:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

typescript TypeScript related

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants