The errors are passed through every callback, but in fact, it might be better to throw an error at higher levels. For example, look at the mongodb.js database function. It passes through an error in the callback. However, if there was an error at that level, it might be better to deal with it at that point and just fall back on procces.on('uncaughtException')
It is a lot of extra code each time, dealing with errors in callbacks. I am wondering if there is a better way around it.
controllers/users.js
var usersModel = require('../models/users.js');
users.create = function(req, res){
usersModel.create(req.data.username, req.data.password, function(error, user){
if(error){
res.statusCode = 500;
res.end('server-error');
return;
}
res.statusCode = 201;
res.end(user._id);
});
};
models/users.js
var db = require('../mongodb.js');
module.exports.create = function(username, password, callback){
db.collection('main', 'users', function(error, collection){
if(error){
callback(error);
return;
}
collection.insert({
username: username,
password: password,
createdOn: new Date()
}, callback);
});
};
mongodb.js
var mongo = require('mongodb')
, mongodb = module.exports
, connections = {}
, config = {
main: {
name: 'application-main',
server: new mongo.Server('127.0.0.1', 27017, { auto_reconnect: true })
}
};
mongodb.database = function(key, callback){
if(connections[key]){
callback(null, connections[key]);
return;
}
var db = mongo.Db(config[key].name, config[key].server);
db.open(function(error, connection){
if(error){
callback(error);
return;
}
connection.on('close', function(){
delete(connections[key]);
});
connections[key] = connection;
callback(null, connection);
}
};
mongodb.collection = function(dbKey, collName, callback){
mongodb.database(dbKey, function(error, connection){
if(error){
callback(error);
return;
}
connection.collection(collName, function(error, collection){
if(error){
callback(error);
return;
}
callback(null, collection);
});
});
};