Friday, April 06, 2012

Taking Toddler Steps with Node.js - Express Error Handling

In the previous post I wrote about my personal routing flavor for Express. For this post, I want to briefly discuss how to set up error handling using Express.

In order to get up and going very quickly, we only need to add the errorHandler middleware provided by Connect.

application.use(express.errorHandler({ showStack: true, dumpExceptions: true }));

Here we configured the errorHandler middleware to report on exceptions and show the stack trace as well. This is quite handy during development as this setup provides us with enough detail.

image

But this is not very effective when we want to move our application to a production environment. When deployed into production, we usually want to show a user-friendly message instead of technical details, stack traces and what not. In this case we can use the application.error() method. This function receives all errors thrown by the regular route functions or errors passed to the next() function. In this catch-all-errors function we can simply render our own custom view.

application.error(function(error, request, response, next) {
    response.render('500', {
        status: 500,
        error: util.inspect(error),
        showDetails: application.settings.showErrorDetails
    });
});

This is how our custom error page looks like:

image

We can also use the application.error() function for rendering custom pages for all kinds of specific errors. Suppose we want to render a custom page for ‘404 – Page Not Found’ errors. Quite easy. We just need to register a catch-all route after all the regular route functions that simply throws a custom error.

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

PageNotFoundError.prototype.__proto__ = Error.prototype;

application.use(function(request, response, next) {
    next(new PageNotFoundError())        
});

Next we need to enhance application.error() function so that it appropriately handles our PageNotFoundError.

application.error(function(error, request, response, next) {
    if (typeof error === typeof PageNotFoundError) {
      response.render('404', {
        status: 404
      });
    } 
    else {
        response.render('500', {
            status: 500,
            error: util.inspect(error),
            showDetails: application.settings.showErrorDetails
        });
    }
});

As you can see, error handling is quite easy to setup for different environments using Express.

Until next time.

No comments: