You can handle Zod validation errors using hooks. You can provide a hook locally at the route level or globally for the entire application.
Local Hook
Pass a third argument to app.openapi() to intercept the result of the validation. If result.success is false, you can return a custom error response.
Global Hook (DRY approach)
Initialize OpenAPIHono with a defaultHook to apply a common error formatter to all routes. Local hooks provided in app.openapi() will override the defaultHook.
// Global Hook
const app = new OpenAPIHono({
defaultHook: (result, c) => {
if (!result.success) {
return c.json({
ok: false,
errors: "formatted_errors",
source: "custom_error_handler",
}, 422);
}
},
});
// Local Hook (Overrides defaultHook)
app.openapi(
createRoute({ /* ... */ }),
(c) => { /* ... */ },
(result, c) => {
if (!result.success) {
return c.json({ ok: false, source: "routeHook" as const }, 400);
}
}
);