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 stack, it will basically wrap the entire stack, which is yielded to downstream, in a giant try/catch
clause. Now we don't need to worry about exceptions being thrown into the ether. In fact, you are now encouraged to throw
common...