Skip to content

验证器中的错误处理

🌐 Error handling in Validator

通过使用验证器,你可以更轻松地处理无效输入。这个示例显示了你可以利用回调结果来实现自定义错误处理。

🌐 By using a validator, you can handle invalid input more easily. This example shows you can utilize the callback result for implementing custom error handling.

虽然这个片段使用了 Zod 验证器,但你可以对任何支持的验证器库采用类似的方法。

🌐 Although this snippet employs Zod Validator, you can apply a similar approach with any supported validator library.

ts
import * as z from 'zod'
import { zValidator } from '@hono/zod-validator'

const app = new Hono()

const userSchema = z.object({
  name: z.string(),
  age: z.number(),
})

app.post(
  '/users/new',
  zValidator('json', userSchema, (result, c) => {
    if (!result.success) {
      return c.text('Invalid!', 400)
    }
  }),
  async (c) => {
    const user = c.req.valid('json')
    console.log(user.name) // string
    console.log(user.age) // number
  }
)

另请参阅

🌐 See also

Hono 中文网 - 粤ICP备13048890号