Koa: How to take advantage of Koa's control flow benefits?

Created on 19 Aug 2016  路  3Comments  路  Source: koajs/koa

I'm coming from Express and love what you guys are doing here. The response-time middleware is an awesome example of how to leverage koa's downstream/upstream flow. However, I haven't been able to find any other good examples like that. As a result, it's been a bit hard for me to figure out how to "think in koa" and figure out how to leverage this in a real app.

Does anyone have any good resources or examples of real apps to help transform my linear-express thinking into koa-thinking?

Most helpful comment

@wlingke another example is error handling. In Express, if you forget to catch errors and pass them along the middleware chain, you're toast.

In Koa, it's as delightful as adding error handling middleware as the first middleware:

app.use(async (ctx, next) => {
  try {
    await next()
  } catch(err) {
    // Handle errors like a boss
    ctx.body = { message: err.message }
    ctx.status = 500
  }
})

Any middleware added after the error handler will run inside that try-catch. Lovely!

All 3 comments

Primarily it's just helpful for global or near-global logic like say you provide ?pretty as a JSON output option in your API, with Express you'd need to hack res.json() or provide your own method, which is also a bit of a hack, with Koa you'd just do ctx.body = { stuff } and forget about it. Upstream you would apply that logic.

@wlingke another example is error handling. In Express, if you forget to catch errors and pass them along the middleware chain, you're toast.

In Koa, it's as delightful as adding error handling middleware as the first middleware:

app.use(async (ctx, next) => {
  try {
    await next()
  } catch(err) {
    // Handle errors like a boss
    ctx.body = { message: err.message }
    ctx.status = 500
  }
})

Any middleware added after the error handler will run inside that try-catch. Lovely!

Thanks guys!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

felixfbecker picture felixfbecker  路  5Comments

ElegantScripting picture ElegantScripting  路  5Comments

xinshouke picture xinshouke  路  4Comments

TheRav3n picture TheRav3n  路  3Comments

sibelius picture sibelius  路  3Comments