Skip to content
Jonathan Ong edited this page Oct 15, 2013 · 14 revisions

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.

app.use(function (next) {
  return function* () {
    try {
      yield next;
    } catch (err) {
      this.status = err.status || 500;
      this.body = err.message || require('http').STATUS_CODES[this.status];
    }
  }
})

app.use(function (next) {
  return function* () {
    throw new Error('some error');
  }
})

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.

Catching stream errors

If you don't use domains, you will have to attach an error handler to each stream you create otherwise any error will crash your app. The easiest way is to use this.onerror():

app.use(function (next) {
  return function* () {
    var stream = new Stream.PassThrough();
    var transform = new Stream.Transform();
    this.body = transform;
    stream.on('error', this.onerror);
    transform.on('error', this.onerror);
    stream.pipe(transform);
  }
})

this.onerror is already bound to this, so you do not have to do stream.on('error', this.onerror.bind(this)).

Note that koa automatically adds this.body.on('error', this.onerror) if the body is a stream. However, you should still add the listener yourself since some middleware, such as compress, will replace the body before koa has a chance to add the error handler.

Clone this wiki locally