Middleware shouldn't be async
rchl opened this issue · comments
Middleware created by this module is an async function. That is incorrect because connect framework doesn't await middleware it runs so any exception within the middleware won't be caught and propagated properly.
I don't see a good way to fix it besides dropping support for async to
functions.
I've noticed this problem while investigating error that can trigger on res.setHeader
with URL with invalid characters (error TypeError [ERR_INVALID_CHAR]: Invalid character in header content ["Location"]
).
@rchl Thanks for pointing that out! Could you create a "failing" example for that?
Not sure if you mean testcase or theoretical example. I don't have time for former now but you can trigger decode failure with URL like %E0%A4%A
and then you'll see that nuxt doesn't generate error page for that (in dev mode). It should if error is caught properly.
BTW. I've just noticed that latest code on the branch is catching errors from decodeURI
which is nice, but it should also catch errors from setHeader
as this can throw independently (as evident from my errors logged by Sentry).
Adding @juno-yu who added async handling in case he has different opinion.
Actually, now that I think about it, it's not really a problem to have an async middleware as long as you are catching errors and passing to next() function.
You can add big try/catch on whole code or something cleaner like an async wrapper function:
function asyncMiddleware(endpointHandlerFunction) {
return function(req, res, next) {
Promise.resolve(endpointHandlerFunction(req, res, next)).catch(next);
};
};
and then wrap original middleware function like:
return asyncMiddleware(async function (req, res, next) {
...
})
Per my last comment, async middleware is not really a problem. Problem is if some of the exceptions are not caught but after #52 all are handled so this is fixed.