Skip to content

Commit

Permalink
fix: surface deepest error from failed union validation
Browse files Browse the repository at this point in the history
The "Expected union value" error message is practically useless, so I think it‘s a better DX to surface the deepest validation error (based on property path).
  • Loading branch information
aleclarson committed Mar 8, 2024
1 parent abe71c6 commit b369c98
Showing 1 changed file with 11 additions and 4 deletions.
15 changes: 11 additions & 4 deletions src/errors/errors.ts
Expand Up @@ -513,14 +513,21 @@ function* FromUndefined(schema: TUndefined, references: TSchema[], path: string,
if (!IsUndefined(value)) yield Create(ValueErrorType.Undefined, schema, path, value)
}
function* FromUnion(schema: TUnion, references: TSchema[], path: string, value: any): IterableIterator<ValueError> {
let count = 0
let unionErrors: ValueError[] | undefined
for (const subschema of schema.anyOf) {
const errors = [...Visit(subschema, references, path, value)]
if (errors.length === 0) return // matched
count += errors.length
if (unionErrors) {
for (const error of errors) unionErrors.push(error)
} else {
unionErrors = errors
}
}
if (count > 0) {
yield Create(ValueErrorType.Union, schema, path, value)
if (unionErrors) {
const pathDepth = (error: ValueError) => error.path.split('/').length
yield unionErrors.reduce(
(deepestError, error) => (!deepestError || pathDepth(error) > pathDepth(deepestError) ? error : deepestError)
)
}
}
function* FromUint8Array(schema: TUint8Array, references: TSchema[], path: string, value: any): IterableIterator<ValueError> {
Expand Down

0 comments on commit b369c98

Please sign in to comment.