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 2e3cb16
Showing 1 changed file with 4 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/errors/errors.ts
Expand Up @@ -514,13 +514,16 @@ function* FromUndefined(schema: TUndefined, references: TSchema[], path: string,
}
function* FromUnion(schema: TUnion, references: TSchema[], path: string, value: any): IterableIterator<ValueError> {
let count = 0
let deepestError: ValueError | undefined
for (const subschema of schema.anyOf) {
const errors = [...Visit(subschema, references, path, value)]
if (errors.length === 0) return // matched
count += errors.length
const pathDepth = (error: ValueError) => error.path.split('/').length
deepestError = errors.reduce((deepestError, error) => (!deepestError || pathDepth(error) > pathDepth(deepestError) ? error : deepestError), deepestError)
}
if (count > 0) {
yield Create(ValueErrorType.Union, schema, path, value)
yield deepestError || Create(ValueErrorType.Union, schema, path, value)
}
}
function* FromUint8Array(schema: TUint8Array, references: TSchema[], path: string, value: any): IterableIterator<ValueError> {
Expand Down

0 comments on commit 2e3cb16

Please sign in to comment.