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

Closed
quark-ftc opened this issue Dec 15, 2024 · 2 comments · Fixed by #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
Contributor

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)
yusukebe pushed a commit that referenced this issue Dec 25, 2024
* docs(zod-validator): add usage docs for `zErrValidator`, throw a validating error instead of directly returning an error response. (#890)

* docs(zod-validator): change zod error to Hono HTTPException

* remove useless generic
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment