O'Reilly logo

Express.js Blueprints by Ben Augarten, Marc Kuo, Eric Lin, Aidha Shaikh, Fabiano Pereira Soriani, Geoffrey Tisserand, Chiqing Zhang, Kan Zhang

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Validation and error handling

Error-handling is one of the fortes of Koa.js. Using generator functions we don't need to deal with error handling in every level of the callbacks, avoiding the use of (err, res) signature callbacks popularized by Node.js. We don't even need to use the .error or .catch methods known to Promises. We can use plain old try/catch that ships with JavaScript out of the box.

The implication of this is that we can now have the following centralized error handling middleware:

var logger = console;

module.exports = function *(next) {
  try {
    yield next;
  } catch (err) {
    this.status = err.status || 500;
    this.body = err.message;
    this.app.emit('error', err, this);
  }
};

When we include this as one of the first middlewares on the Koa ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required