Skip to content

Commit

Permalink
feat(hono-base): skip import HTTPException by using HTTPResponseError (
Browse files Browse the repository at this point in the history
…#2898)

This change is intended to make error handling more flexible and reduce bundle size.
This idea is originated from #2885

Co-authored-by: Yusuke Wada <[email protected]>
  • Loading branch information
usualoma and yusukebe authored Jun 3, 2024
1 parent d260d21 commit 524296e
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 4 deletions.
6 changes: 3 additions & 3 deletions src/hono-base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import { compose } from './compose'
import { Context } from './context'
import type { ExecutionContext } from './context'
import { HTTPException } from './http-exception'
import { HonoRequest } from './request'
import type { Router } from './router'
import { METHODS, METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE } from './router'
Expand All @@ -16,6 +15,7 @@ import type {
ErrorHandler,
FetchEventLike,
H,
HTTPResponseError,
HandlerInterface,
MergePath,
MergeSchemaPath,
Expand All @@ -38,8 +38,8 @@ const notFoundHandler = (c: Context) => {
return c.text('404 Not Found', 404)
}

const errorHandler = (err: Error, c: Context) => {
if (err instanceof HTTPException) {
const errorHandler = (err: Error | HTTPResponseError, c: Context) => {
if ('getResponse' in err) {
return err.getResponse()
}
console.error(err)
Expand Down
20 changes: 20 additions & 0 deletions src/hono.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1479,6 +1479,26 @@ describe('Error handle', () => {
expect(await res.text()).toBe('Custom Error Message')
})
})

describe('Handle HTTPException like object', () => {
const app = new Hono()

class CustomError extends Error {
getResponse() {
return new Response('Custom Error', { status: 400 })
}
}

app.get('/exception', () => {
throw new CustomError()
})

it('Should return 401 response', async () => {
const res = await app.request('http://localhost/exception')
expect(res.status).toBe(400)
expect(await res.text()).toBe('Custom Error')
})
})
})

describe('Error handling in middleware', () => {
Expand Down
6 changes: 5 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,12 @@ export type H<
> = Handler<E, P, I, R> | MiddlewareHandler<E, P, I>

export type NotFoundHandler<E extends Env = any> = (c: Context<E>) => Response | Promise<Response>

export interface HTTPResponseError extends Error {
getResponse: () => Response
}
export type ErrorHandler<E extends Env = any> = (
err: Error,
err: Error | HTTPResponseError,
c: Context<E>
) => Response | Promise<Response>

Expand Down

0 comments on commit 524296e

Please sign in to comment.