Understanding error handlers #1752
eduardvercaemer
started this conversation in
General
Replies: 2 comments
-
Btw my actual middleware looks something like this using the c.error thing: await sql
.begin(async (sql) => {
c.set("sql", sql);
await next();
if (c.error) {
console.debug("Rolling back transaction");
throw new Error();
}
})
.catch((_) => {}); So is this at least how it should be done the 'hono' way? |
Beta Was this translation helpful? Give feedback.
0 replies
-
Currently, to ensure it runs as expected, you should write the handler that might throw an error at the top: app.get('/error', async (c) => {
throw new Error('error')
})
app.use('*', async (c, next) => {
console.log('before!')
await next()
console.log('after!')
}) This may not be the best API, but Hono also needs to handle error responses depending on user requests. So, if you want to stop the operation as soon as you throw an error, write it above. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I'm was trying to setup a really simple error handler, but I just can't get my head arround
onError
.This is my minimal example (Im using bun as runtime)
I expect an error handler to act as a top level middleware that catches any error that escapes the handling chain and return a final response. Instead, it looks like it is handling the error in the inner most handler and then continues execution of my middleware which I think is not what a user wants most of the time (please correct me if I'm wrong). If a user wants to allow exceptions in their middleware they explicitly wrap their
next
in a try catch or use a then-catch chain.I then tried to use a middleware error handler instead:
but the exact same thing happens? I imagine a default
onError
is doing something and avoiding my handler to throw into my middleware as I want it to, so now I need to also set a handler to throw:My actual use case is transaction middleware, if the handler does not throw then it obviously does not work. An alternative I can think of is using the c.error proeprty in the middleware to check if an error occured inside of my middleware but IMHO it feels weird to do error handling this way??
Beta Was this translation helpful? Give feedback.
All reactions