Better error handling for Union (not Discriminated Unions) #1111
Lonli-Lokli
started this conversation in
General
Replies: 1 comment 3 replies
-
@Lonli-Lokli Hi, You can obtain union variant errors by accessing the const error = TypeCompiler.Compile(multi).Errors(data).First()!;
console.log(error) // {
// type: 62,
// schema: { anyOf: [ [Object], [Object] ], [Symbol(TypeBox.Kind)]: 'Union' },
// path: '/schema',
// value: { panel: { id: 1, title: 1 } },
// message: 'Expected union value',
// errors: [
// ValueErrorIterator2 { iterator: Object [Generator] {} }, // firstOption
// ValueErrorIterator2 { iterator: Object [Generator] {} } // secondOption
// ]
// }
console.log(error.errors[0].First()) // {
// type: 45,
// schema: { type: 'string', [Symbol(TypeBox.Kind)]: 'String' },
// path: '/schema/key_column',
// value: undefined,
// message: 'Expected required property',
// errors: []
// }
console.log(error.errors[1].First()) // {
// type: 54,
// schema: {
// type: 'string',
// [Symbol(TypeBox.Kind)]: 'String',
// [Symbol(TypeBox.Optional)]: 'Optional'
// },
// path: '/schema/panel/id',
// value: 1,
// message: 'Expected string',
// errors: []
// } To extract all errors, you will likely want to write a recursive function to pull the errors out. // ...
type MappedError = [{ message: string, path: string, errors: MappedError[] }]
const MapErrorIterator = (iterator: ValueErrorIterator): MappedError[] => (
[...iterator].map(error => MapError(error)) as never
)
const MapError = (error: ValueError) => ({
message: error.message,
path: error.path,
errors: error.errors.map(iterator => MapErrorIterator(iterator))
})
// ...
const R = MapErrorIterator(TypeCompiler.Compile(multi).Errors(data)) // [
// {
// message: 'Expected union value',
// path: '/schema',
// errors: [
// [
// {
// message: 'Expected required property',
// path: '/schema/key_column',
// errors: []
// },
// {
// message: 'Expected string',
// path: '/schema/key_column',
// errors: []
// },
// {
// message: 'Expected string',
// path: '/schema/panel/id',
// errors: []
// }
// ],
// [
// {
// message: 'Expected string',
// path: '/schema/panel/id',
// errors: []
// },
// {
// message: 'Expected string',
// path: '/schema/panel/title',
// errors: []
// }
// ]
// ]
// }
// ] TypeBox doesn't currently provide any utility methods to extract or map errors. So you will need to use the above to map the errors into forms accepted by your application. Hope this helps |
Beta Was this translation helpful? Give feedback.
3 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Given this code, there is no way for me to get proper error
What are you usually doing for this?
Beta Was this translation helpful? Give feedback.
All reactions