Skip to content

Validator에서 오류 처리하기

Validator를 사용하면 유효하지 않은 입력을 더 쉽게 처리할 수 있다. 이 예제에서는 콜백 결과를 활용해 커스텀 오류 처리를 구현하는 방법을 보여준다.

이 코드 조각은 Zod Validator를 사용하지만, 지원되는 다른 Validator 라이브러리에서도 비슷한 접근 방식을 적용할 수 있다.

ts
import { 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
  }
)

관련 자료

Released under the MIT License.