diff --git a/src/hono-base.ts b/src/hono-base.ts index f3e9ad030..79d85db6e 100644 --- a/src/hono-base.ts +++ b/src/hono-base.ts @@ -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' @@ -16,6 +15,7 @@ import type { ErrorHandler, FetchEventLike, H, + HTTPResponseError, HandlerInterface, MergePath, MergeSchemaPath, @@ -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) diff --git a/src/hono.test.ts b/src/hono.test.ts index 7dc81526d..28df32f8a 100644 --- a/src/hono.test.ts +++ b/src/hono.test.ts @@ -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', () => { diff --git a/src/types.ts b/src/types.ts index 2178e5c1b..87691b015 100644 --- a/src/types.ts +++ b/src/types.ts @@ -91,8 +91,12 @@ export type H< > = Handler | MiddlewareHandler export type NotFoundHandler = (c: Context) => Response | Promise + +export interface HTTPResponseError extends Error { + getResponse: () => Response +} export type ErrorHandler = ( - err: Error, + err: Error | HTTPResponseError, c: Context ) => Response | Promise