hono: Sub-Instances of Hono don't trigger onError
Hi!
I’m currently restructuring my project’s routes to use multiple sub-instances for their respective category. Hono supports grouping multiple instances with hono.route(), though it seems like it’s not possible to define a custom error handler for a sub-instance.
Here is my example code:
import { Hono } from "hono";
import { serve } from "https://deno.land/std/http/server.ts";
const hono = new Hono();
const route = new Hono();
route.onError((err, ctx) => {
return ctx.text("Caught error!", 500);
});
route.get("/", (ctx) => {
throw new Error("Unhandled Error.");
});
hono.route("/", route);
serve(hono.fetch, { port: 3000 });
The endpoint /, defined by route, will throw an Error. The instance route should catch and handle errors, because of route.onError(...).
Though when hitting the endpoint /, the thrown error gets printed to the console and the API returns 500 - Internal Server Error.
Trace: Error: Unhandled Error.
at file:///workspace/src/server.ts:13:9
at Hono.dispatch (https://deno.land/x/hono@v2.7.5/hono.ts:216:15)
at Server.fetch (https://deno.land/x/hono@v2.7.5/hono.ts:263:17)
at Server.#respond (https://deno.land/std@0.174.0/http/server.ts:299:37)
at Server.#serveHttp (https://deno.land/std@0.174.0/http/server.ts:346:20)
at Hono.errorHandler (https://deno.land/x/hono@v2.7.5/hono.ts:111:13)
at Hono.handleError (https://deno.land/x/hono@v2.7.5/hono.ts:191:19)
at Hono.dispatch (https://deno.land/x/hono@v2.7.5/hono.ts:219:21)
at Server.fetch (https://deno.land/x/hono@v2.7.5/hono.ts:263:17)
at Server.#respond (https://deno.land/std@0.174.0/http/server.ts:299:37)
at Server.#serveHttp (https://deno.land/std@0.174.0/http/server.ts:346:20)
This looks like a bug to me. I appreciate any help!
About this issue
- Original URL
- State: closed
- Created a year ago
- Comments: 15 (13 by maintainers)
Thank you both for the quick response 😊
Hi @nanderLP !
This is not a bug. This is because
hono.route('/', route)is designed to pass the routings ofroutetohono. TheonErrorhandler is not included in the routing. So,onErrorinhonowill be used for any route.I think you are right. It is very difficult to make this possible, but worth a try. Please keep this Issue open for a while. Thanks.