docs(zod-validator): add usage docs for `zErrValidator` (#900)

* 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
pull/904/head
ktKongTong 2024-12-25 09:32:07 +08:00 committed by GitHub
parent c9d96ee6c2
commit 755d5cb84d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 26 additions and 0 deletions

View File

@ -37,6 +37,32 @@ app.post(
)
```
Throw Error:
throw a zod validate error instead of directly returning an error response.
```ts
// file: validator-wrapper.ts
import { ZodSchema } from "zod";
import type { ValidationTargets } from "hono";
import { zValidator as zv } from "@hono/zod-validator";
export const zValidator = (target: keyof ValidationTargets, schema: ZodSchema) =>
zv(target, schema, (result, c) => {
if (!result.success) {
throw new HTTPException(400, { cause: result.error });
}
})
// usage
import { zValidator } from './validator-wrapper'
app.post(
'/post',
zValidator('json', schema)
//...
)
```
## Author
Yusuke Wada <https://github.com/yusukebe>