Validation Errors
Control exactly how validation failures are formatted and returned to the client. Every validation library in MoroJS normalizes to a single shape, so you write one error handler and it works everywhere.
On this page
How Error Handling Works
When a validation schema rejects a request, MoroJS runs the failures through a single pipeline:
- Normalize — raw errors from Zod, Joi, Yup, class-validator, or custom functions are converted to a shared
ValidationErrorDetailType[]. - Resolve handler — the per-route
onValidationErrorwins if present, then the global handler passed tocreateApp(), then the built-in default. - Respond — the handler returns a
ValidationErrorResponse({ status, body, headers? }) which MoroJS writes to the client.
Because the errors array is always the same shape, you never have to branch on which validation library produced a given failure.
Default Response Format
With no custom handler, MoroJS returns a 400 Bad Request with a consistent JSON body listing each failing field.
Default 400 Response (development)
json
The error string names which part of the request failed (body, query, params, or headers). The details array is omitted when NODE_ENV=production to avoid leaking schema internals.
Per-Route Custom Handler
Pass onValidationError on any route to override the response shape for that route only.
Custom Handler on a Route (chainable API)
typescript
On a Module Route
typescript
What you get in the handler
- •
errors— normalized failure list, always the same shape regardless of validation library - •
context.field— which request part failed (body,query, etc.) - •
context.request—method,url,path,headers - •
context.route— matched route method/path when available
Global Handler
Set one handler at app construction and every unvoiced route inherits it. Individual routes can still override with onValidationError.
App-Wide Validation Handler
typescript
Resolution Order
- Per-route
onValidationError - Global handler from
createApp({ validation }) - Built-in default (400 + normalized body)
Type Reference
ValidationErrorHandler
typescript
ValidationErrorDetailType
typescript
ValidationErrorContext
typescript
ValidationErrorResponse
typescript