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 genericpull/904/head
parent
c9d96ee6c2
commit
755d5cb84d
|
@ -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
|
## Author
|
||||||
|
|
||||||
Yusuke Wada <https://github.com/yusukebe>
|
Yusuke Wada <https://github.com/yusukebe>
|
||||||
|
|
Loading…
Reference in New Issue