4 ms·
This isn't an issue if you're using promises. You can use try/catch from within async functions and it works exactly as you'd expect. A few years before async
by TheAceOfHearts 8y ago
This isn't an issue if you're using promises. You can use try/catch from within async functions and it works exactly as you'd expect.
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/co https://github.com/tj/co
- hombre_fatal 8y agoThe other main difference between koa and express is that, in express, you send responses from handlers while in koa, you bubble up a {req,res} context back to koa which sends it which gives you real middleware since you can still mutate the response. The 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.