Skip to content

[FEATURE] expose validation error hook in Hono adapter #13465

Description

@abrahamcl

Problem Statement

With @hono/zod-openapi, its possible to intercept validation error using hooks:

const app = new OpenAPIHono({
  defaultHook: (result, c) => {
    if (!result.success) {
      return c.json(
        {
          ok: false,
          errors: formatZodErrors(result),
          source: 'custom_error_handler',
        },
        422
      )
    }
  },
})

This is necessary to create custom API responses depending on the specifics of the Zod error.

Proposed Solution

Add defaultValidationHook?: (err: z.core.$ZodError): JSONRespond to MastraServer constructor
Add validationHook?: (err: z.core.$ZodError): JSONRespond to createRoute

Note: JSONRespond is specific to Hono.

Thread any validation errors through these hooks if provided.

Component

Deployment

Alternatives Considered

  • Modify zod schemas directly: any custom errors is still wrapped by Mastra's default 400
  • Catch validation errors with a middleware. At the middleware level, there is no way to differentiate between validation errors and errors that happened in the route handler.

Example Use Case

As a developer, I want to conform to my companies API standards, which includes specifically formatted error messages for validation errors. Doing this in Mastra is currently very hacky.

Additional Context

No response

Verification

  • I have searched the existing issues to make sure this is not a duplicate
  • I have provided sufficient context for the team to understand the request

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions