-
Notifications
You must be signed in to change notification settings - Fork 155
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Custom errors using TypeCompiler #500
Comments
@JimSalies Hi, TypeBox doesn't handle automatic custom error messages internally, rather it requires implementers to remap the error objects yielded on const T = Type.Object({
x: Type.Number({ errorMessage: 'X error' }),
y: Type.Number({ errorMessage: 'Y error' }),
z: Type.Number({ errorMessage: 'Z error' }),
})
const C = TypeCompiler.Compile(T)
// The failing schema is passed as a property on each `error` object. You can inspect
// the schema and remap for any custom metadata found on it if necessary. Note, you
// would typically wrap the following up in a function and use it in your applications
// validation pipeline.
const E = [...C.Errors({ x: '1', y: '2', z: '3' })].map(error => {
return (typeof error.schema.errorMessage === 'string')
? {...error, message: error.schema.errorMessage}
: {...error }
})
console.log(E) // const E = [
// {
// type: 29,
// schema: {
// errorMessage: 'X error',
// type: 'number',
// [Symbol(TypeBox.Kind)]: 'Number'
// },
// path: '/x',
// value: '1',
// message: 'X error' // message mapped here
// },
// {
// type: 29,
// schema: {
// errorMessage: 'Y error',
// type: 'number',
// [Symbol(TypeBox.Kind)]: 'Number'
// },
// path: '/y',
// value: '2',
// message: 'Y error' // message mapped here
// },
// {
// type: 29,
// schema: {
// errorMessage: 'Z error',
// type: 'number',
// [Symbol(TypeBox.Kind)]: 'Number'
// },
// path: '/z',
// value: '3',
// message: 'Z error' // message mapped here
// }
// ] TypeBox keeps error functionality quite raw and doesn't make assumptions as to how users need their errors structured, and there are a number of ways you wrap up the above logic. However if you just need something to quickly remap errors for you, have a look at https://github.com/jtlapp/typebox-validators which provides custom error mapping plus several other validation features. Hope this helps! |
@JimSalies Hiya, Might close off this issue. If you have any additional follow up questions, please feel free to respond on this thread. All the best! |
Thank you for this quick answer. It's exactly what I was looking for. |
First of all, thank you for this amazing lib!
I have been searching through documentation / PR and discussions and didn't find anything about using custom errors with typecompiler. Is it possible to use custom error messages? If so, how to do it?
The text was updated successfully, but these errors were encountered: