Skip to content

예외 처리

인증 실패와 같은 치명적인 오류가 발생할 경우, HTTPException을 반드시 던져야 한다.

HTTPException 던지기

이 예제는 미들웨어에서 HTTPException을 던지는 방법을 보여준다.

ts
import { Hono } from 'hono'
const app = new Hono()
declare const authorized: boolean
// ---cut---
import { HTTPException } from 'hono/http-exception'

// ...

app.post('/auth', async (c, next) => {
  // 인증 처리
  if (authorized === false) {
    throw new HTTPException(401, { message: '커스텀 에러 메시지' })
  }
  await next()
})

사용자에게 반환할 응답을 직접 지정할 수도 있다.

ts
import { HTTPException } from 'hono/http-exception'

const errorResponse = new Response('Unauthorized', {
  status: 401,
  headers: {
    Authenticate: 'error="invalid_token"',
  },
})

throw new HTTPException(401, { res: errorResponse })

HTTPException 처리하기

app.onError를 사용해 발생한 HTTPException을 처리할 수 있다.

ts
import { Hono } from 'hono'
const app = new Hono()
// ---cut---
import { HTTPException } from 'hono/http-exception'

// ...

app.onError((err, c) => {
  if (err instanceof HTTPException) {
    // 커스텀 응답을 가져온다
    return err.getResponse()
  }
  // ...
  // ---cut-start---
  return c.text('Error')
  // ---cut-end---
})

cause 옵션

cause 옵션은 cause 데이터를 추가할 때 사용한다.

ts
import { Hono, Context } from 'hono'
import { HTTPException } from 'hono/http-exception'
const app = new Hono()
declare const message: string
declare const authorize: (c: Context) => void
// ---cut---
app.post('/auth', async (c, next) => {
  try {
    authorize(c)
  } catch (e) {
    throw new HTTPException(401, { message, cause: e })
  }
  await next()
})

Released under the MIT License.