Skip to content
Malcolm edited this page Mar 29, 2017 · 14 revisions

Error handling is much easier in koa. You can finally use try/catch!

Catching downstream errors

In Express, you caught errors by adding an middleware with a (err, req, res, next) signature as one of the last middleware. In contrast, in koa you add a middleware that does try { await next() } as one of the first middleware. It is also recommended that you emit an error on the application itself for centralized error reporting, retaining the default behaviour in Koa.

app.use(async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    ctx.status = err.status || 500;
    ctx.body = err.message;
    ctx.app.emit('error', err, this);
  }
});

app.use(async (ctx, next) => {
  //This will set status and message
  ctx.throw('Error Message', 500);
}); 

app.use(async (ctx, next) => {
  //This will only set message
  throw new Error('Error Message');
});

This opens up a bunch of new possibilities:

  • As you go down the stack, you can change error handlers very easily.
  • You can handle errors in portions of your code much more easily.
Clone this wiki locally