Intercepting Callbacks using Domain in Node.js

If you are not aware of what domain is then i will suggest you to give my previous post a read which explains exceptions and domains in node.js.

Domains as we all know provide us for better expection handling, on the other hand it also enables us to intercept callbacks to rule out the errors. This will get more clear with the example below:

    User.find({'user': 'Suroor Wijdan'}, function(err, user){
        if(err) {
            return err;
        } else {
            return user;

If we look at the code snippet above, as a common practice the first argument of our callback is always error and the second argument is the data. To check if there is an error we have to place if statements. I particularly don't like doing this over and over again for each of the database calls.

Ruling out if statements with domain.intercept

What domain does is, it intercepts the first error argument along with any other thrown errors. Thus leaving us with the required data object we are looking for from the callback. All the errors are taken care of by single error handler. The modified code snippet above looks as below when using domain.intercept.

    var domain = require('domain');

    User.find({'user': 'Suroor Wijdan'}, domain.intercept(function(user){
        return user; //No need for if statements anymore

    //Single error handler for all the errors
    domain.on('error', function(error){  

As you can see in the example above, we rule out the if(err) return err; statements altogheter. Also the code looks more clean and dry using this method.

domain is still marked as unstable in the official documentation, so i will suggest you to give it a thought before using it on production.

Let me know if you see any improvements for this blog. Cheers!

comments powered by Disqus