Expressive way to handle errors in expressjs

When you have created new express project, the errors get handled a bit differently in dev mode and in production mode. In development mode the errors are show in express error template with some error stack if showStack is set to true. But in production mode you will be shown as less as you need the ‘Internal Server Error’ on plain text page. Here is our plan to make the production side errors more fancier and keep the development side informative.

First take of the production mode default error handling.

app.configure('production', function(){
  //app.use(express.errorHandler()); 
});

Add app.error which will be run on if error is caught. I have already created views for errors which needs some customization on jade template.

app.error(function(err, req, res, next){
  if (err instanceof NotFound) {
    res.render('error/404.jade', { title: 'Not found 404' });
  } else {
    res.render('error/500.jade', { title: 'Error', error: err });
  }
});

And in the end of app.js, added the /* router which routes all the unknown pages to 404 page by throwing NotFound errror. So by going to url like this localhost:3000/path/that/does/not/exist does not lead you to the some GET that route does not exist, but into 404 page.

// The 404
app.get('/*', function(req, res){
    throw new NotFound;
});

function NotFound(msg){
    this.name = 'NotFound';
    Error.call(this, msg);
    Error.captureStackTrace(this, arguments.callee);
}

Running now the server in production mode NODE_ENV=production node app.js, should give on visiting unknown page this:

And on the 500 error which are thrown when user tries to go in /add/post page without permission:

This is one way to handle the errors in expressjs, if you know any better methods feel free to post. The code is also added into github.

Advertisements