Error Handling

Kyle Baldwin edited this page Jul 9, 2015 · 8 revisions
Clone this wiki locally

Thanks to co, 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 { yield 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(function *(next) {
  try {
    yield next;
  } catch (err) {
    this.status = err.status || 500;
    this.body = err.message;
    this.app.emit('error', err, this);
  }
});

app.use(function *(next) {
  //This will set status and message
  this.throw('Error Message', 500);
}); 

app.use(function *(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.