title: Node.js proper callback error handle
body: <p>Lets take a look at the following code:</p>
  
  <p><em><strong>mongodb.js</em></strong></p>
  
  <pre><code>var mongo = require('mongodb')
    , mongodb = module.exports;
  
  mongodb.database = function(key, dbName, dbServer, callback){
    var db = new mongo.Db(dbName, dbServer);
    db.open(function(error, connection){ // 5
      if(error){ // 1
        throw error;
      }
  
      return callback(null, connection);
    });
  };
  
  mongodb.collection = function(dbKey, collName, callback){
    mongodb.database(dbKey, function(error, connection){
      connection.collection(collName, function(error, collection){ // 2
        if(error){ // 3
          throw error;
        }
  
        return callback(null, collection);
      });
    });
  }
  </code></pre>
  
  <p><em><strong>model.js</em></strong></p>
  
  <pre><code>var db = require('./mongodb.js');
  var model = module.exports;
  
  model.test = function(callback){
    db.collection('users', function(error, collection){ // 4
      // do something.
    });
  }
  </code></pre>
  
  <p>My question is, why do we always do "error, resource" when a callback is passed through, because, take a look at <strong><em>1</em></strong></p>
  
  <p>We are dealing with the error, so it can't even reach <strong><em>2</em>*</strong></p>
  
  <p>Same with <strong><em>3</em></strong> and <strong><em>4</em></strong> they will always be NULL, because the error is handled on a different layer. Now why wouldn't I just do this at <strong><em>5</em></strong>:</p>
  
  <pre><code>db.open(function(error, connection){
    if(error){ // 1
      return errorHandler(error);
    }
  
    return callback(collection);
  });
  </code></pre>
  
  <p>the errorHandler function would be a function that deals with major errors, so we don't have to use them at each layer, same story for for example mongodb.findOne, why do we have to deal with errors when we pass in the callback?</p>