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

Allow custom exception handling in built-in middlewares #3757

Open
nidib opened this issue Dec 19, 2024 · 2 comments
Open

Allow custom exception handling in built-in middlewares #3757

nidib opened this issue Dec 19, 2024 · 2 comments
Labels
enhancement New feature or request.

Comments

@nidib
Copy link

nidib commented Dec 19, 2024

What is the feature you are proposing?

Description

Currently, Hono's middlewares, such as csrf, throw HTTPException by default. However, there is no simple way to customize this behavior to throw a specific application-layer exception.

To achieve this, developers need to wrap the middleware with a try-catch block and rethrow a custom exception, as shown below:

const customCsrf: typeof csrf = options => {
    return createMiddleware(async (c, next) => {
        try {
            const middleware = csrf(options);
            await middleware(c, next);
        } catch (e) {
            if (e instanceof HTTPException) {
                throw new CustomException();
            }

            throw e;
        }
    });
}

const app = new Hono();

app.use(customCsrf());

While this works, it introduces unnecessary boilerplate code.

Proposed Change

Add an optional exception property to specify a custom exception class:

const app = new Hono();

app.use(csrf({ exception: CustomException }))

If an exception is provided, the middleware throws that instead of the default HTTPException. The original exception could be preserved in the cause property for debugging purposes.

Benefits

  • Reduces boilerplate code.
  • Maintains backward compatibility by defaulting to HTTPException.
@nidib nidib added the enhancement New feature or request. label Dec 19, 2024
@EdamAme-x
Copy link
Contributor

I believe you can create your own custom middleware.

app.use(catchError({ exception: CustomException, middleware: csrf() }))

@nidib
Copy link
Author

nidib commented Dec 20, 2024

I believe you can create your own custom middleware.

app.use(catchError({ exception: CustomException, middleware: csrf() }))

That is also a good workaround solution!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request.
Projects
None yet
Development

No branches or pull requests

2 participants