Thursday, March 2, 2017

Koa.js - Error Handling

Error handling plays an important part in building web applications. Koa uses middlewares for this purpose as well.
In koa you add a middleware that does try { yield next } as one of the first middleware. If we encounter any error downstream, we return to the associated catch clause and handle the error here. For example:

var koa = require('koa');
var app = koa();

//Error handling middleware
app.use(function *(next) {
  try {
    yield next;
  } catch (err) {
    this.status = err.status || 500;
    this.body = err.message;
    this.app.emit('error', err, this);
  }
});

//Create an error in the next middleware
//Set the error message and status code and throw it using context object

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

app.listen(3000);
We have deliberately created an error in above code and are handling the error in our first middleware's catch block. This is then emmited to our console as well as sent as the response to our client. Following is the error message we get when we trigger this error.
InternalServerError: Error Message
      at Object.module.exports.throw (/home/ayushgp/learning/koa.js/node_modules/koa/lib/context.js:91:23)
      at Object. (/home/ayushgp/learning/koa.js/error.js:18:13)
      at next (native)
      at onFulfilled (/home/ayushgp/learning/koa.js/node_modules/co/index.js:65:19)
      at /home/ayushgp/learning/koa.js/node_modules/co/index.js:54:5
      at Object.co (/home/ayushgp/learning/koa.js/node_modules/co/index.js:50:10)
      at Object.toPromise (/home/ayushgp/learning/koa.js/node_modules/co/index.js:118:63)
      at next (/home/ayushgp/learning/koa.js/node_modules/co/index.js:99:29)
      at onFulfilled (/home/ayushgp/learning/koa.js/node_modules/co/index.js:69:7)
      at /home/ayushgp/learning/koa.js/node_modules/co/index.js:54:5
Right now any request sent to the server will result in this error.

No comments:

Post a Comment