Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Zod Validator] When the verification fails, can Zod Validator throw an exception instead of directly returning an error message? #890

Open
quark-ftc opened this issue Dec 15, 2024 · 2 comments · May be fixed by #897 or #900

Comments

@quark-ftc
Copy link

When the verification fails, can Zod Validator throw an exception instead of directly returning an error message?

@askorupskyy
Copy link
Contributor

You can use the middleware for this. honojs/hono#960

@ktKongTong
Copy link

This can be handled by a wrapper function:

import {z, ZodSchema} from "zod";
import type {ValidationTargets} from "hono";
import {zValidator as zv} from "@hono/zod-validator";
export const zValidator = <
  T extends ZodSchema,
  Target extends keyof ValidationTargets,
>(
  target: Target,
  schema: T,
) => zv(target, schema, (result, c) => {
  if(!result.success) {
    throw result.error
  }
})

or another version that supports a custom hook

import {z, ZodSchema} from "zod";
import type { ValidationTargets, Env } from "hono";
import { zValidator as zv , type Hook} from "@hono/zod-validator";

export const zValidator = <
  T extends ZodSchema,
  Target extends keyof ValidationTargets,
  E extends Env,
  P extends string
>(
  target: Target,
  schema: T,
  hook: Hook<z.infer<T>, E, P, Target> = (result, _c) => { if(!result.success) throw result.error }
) => zv(target, schema, hook)

ktKongTong added a commit to ktKongTong/middleware that referenced this issue Dec 21, 2024
…dating error instead of directly returning an error response. (honojs#890)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment