Error Provider
There are 2 ways to provide a custom error message when the validation fails:
- inline
error
property - Using onError event
Error Property
Elysia's offers an additional "error" property, allowing us to return a custom error message if the field is invalid.
import { Elysia, t } from 'elysia'
new Elysia()
.post('/', () => 'Hello World!', {
body: t.Object(
{
x: t.Number()
},
{
error: 'x must be a number'
}
)
})
.listen(3000)
The following is an example of usage of the error property on various types:
TypeBox | Error |
typescript
|
|
typescript
|
|
typescript
|
|
typescript
|
|
Error message as function
Over a string, Elysia type's error can also accepts a function to programatically return custom error for each property.
The error function accepts same argument as same as ValidationError
import { Elysia, t } from 'elysia'
new Elysia()
.post('/', () => 'Hello World!', {
body: t.Object({
x: t.Number({
error(error) {
return 'Expected x to be a number'
}
})
})
})
.listen(3000)
TIP
Hover over the error
to see the type
Error is called per field
Please be cautious that the error function will only be called if the field is invalid.
Please consider the following table:
Code | Body | Error |
typescript
| json
| Expected x to be a number |
typescript
| json
| (default error, `t.Number.error` is not called) |
typescript
| json
| Expected value to be an object |
onError
We can customize the behavior of validation based on onError event by narrowing down the error code call "VALIDATION".
import { Elysia, t } from 'elysia'
new Elysia()
.onError(({ code, error }) => {
if (code === 'VALIDATION')
return error.message
})
.listen(3000)
Narrowed down error type, will be typed as ValidationError
imported from 'elysia/error'.
ValidationError exposed a property name validator typed as TypeCheck, allowing us to interact with TypeBox functionality out of the box.
import { Elysia, t } from 'elysia'
new Elysia()
.onError(({ code, error }) => {
if (code === 'VALIDATION')
return error.validator.Errors(error.value).First().message
})
.listen(3000)
Error list
ValidationError provides a method ValidatorError.all
, allowing us to list all of the error causes.
import { Elysia, t } from 'elysia'
new Elysia()
.post('/', ({ body }) => body, {
body: t.Object({
name: t.String(),
age: t.Number()
}),
error({ code, error }) {
switch (code) {
case 'VALIDATION':
console.log(error.all)
// Find a specific error name (path is OpenAPI Schema compliance)
const name = error.all.find((x) => x.path === '/name')
// If has a validation error, then log it
if(name)
console.log(name)
}
}
})
.listen(3000)
For more information about TypeBox's validator, see TypeCheck.