1.9 KiB
1.9 KiB
Home | Installation | Usage | Types | Values | Syntax | TypeRegistry | TypeCheck
Error Function
Error messages in TypeBox can be customized by defining an ErrorFunction. This function allows for the localization of error messages as well as enabling custom error messages for custom types. By default, TypeBox will generate messages using the en-US locale. To support additional locales, you can replicate the function found in src/errors/function.ts and create a locale specific translation. The function can then be set via SetErrorFunction.
The following example shows an inline error function that intercepts errors for String, Number and Boolean only. The DefaultErrorFunction is used to return a default error message.
import {
SetErrorFunction,
DefaultErrorFunction,
ValueErrorType,
} from "@alkdev/typebox/errors";
SetErrorFunction((error) => {
// i18n override
switch (error.errorType) {
/* en-US */ case ValueErrorType.String:
return "Expected string";
/* fr-FR */ case ValueErrorType.Number:
return "Nombre attendu";
/* ko-KR */ case ValueErrorType.Boolean:
return "예상 부울";
/* en-US */ default:
return DefaultErrorFunction(error);
}
});
const T = Type.Object({
// const T: TObject<{
x: Type.String(), // TString,
y: Type.Number(), // TNumber,
z: Type.Boolean(), // TBoolean
}); // }>
const E = [
...Value.Errors(T, {
// const E = [{
x: null, // type: 48,
y: null, // schema: { ... },
z: null, // path: '/x',
}),
]; // value: null,
// message: 'Expected string'
// }, {
// type: 34,
// schema: { ... },
// path: '/y',
// value: null,
// message: 'Nombre attendu'
// }, {
// type: 14,
// schema: { ... },
// path: '/z',
// value: null,
// message: '예상 부울'
// }]
Back to Home