by TheAceOfHearts · 7y ago · 0 comments
My initial reaction to this is "just because you can doesn't mean you should". Perhaps that's a bit harsh, but it seems wasteful to be creating these wrappers instead of just adding the desired functionality directly to your favorite logging library. Did you try bringing it up with the people maintaining the wrapped libraries? It's also worth mentioning that async_hooks is considered an experimental API.
The simpler solution is to stick a unique id in the context object of each request, perhaps passing around a request-specific log function as well if needed. You should have access to it from all your call sites so you can pass it in as needed, and there's no need for magic.
A few years before async functions were available you could also achieve the same thing with generators. In fact, the original release of koa used co [0] under the hood.
I'll note my response is written with koa middleware in mind. I haven't kept up much with express, although I think it should be possible to achieve the same thing since they also support async functions.
With koa you can add a middleware that wraps all downstream middleware in a try/catch:
app.use(async (ctx, next) => {
try {
await next()
} catch (error) {
// handle errors
}
})
[0] https://github.com/tj/coThe promise chaining nature also makes it so that your example handler can catch all downstream errors unlike express where you must call next(err) and handle it in a downstream handler vs koa's upstream middleware pattern (clojure's ring works the same way).
I thank co and early koa for making node bearable for me long before async/await were available.