Error Provider â
There are 2 ways to provide a custom error message when the validation fails:
- inline
message
property - Using onError event
Message Property â
TypeBox 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()
.get('/', () => 'Hello World!', {
body: t.Object(
{
x: t.Number()
},
{
error: 'x must be a number'
}
)
})
.listen(3000)
import { Elysia, t } from 'elysia'
new Elysia()
.get('/', () => '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
|
|
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)
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)
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)
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.