Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(hono-base): skip import HTTPException by using HTTPResponseError #2898

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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