so I am running into what I think is a binding issue, caused by connect-mongo or expressjs Here is the code:
//Error
app.use(function(err, req, res, next) {
if (err instanceof noData) {
res.send(err, 404);
} else {
next(err);
}
});
My custom error handler
function noData(err){
this.code = 0;
this.msg = err;
console.log(Error);
Error.call(this, {code:0, msg:err});
Error.captureStackTrace(this, arguments.callee);
};
noData.prototype.__proto__ = Error.prototype;
Throwing error here:
err = true;
//if(err) throw new noData('No Password');
//Get user from database
db.collection('users').find({}, {limit:1}).toArray(function(err, result) {
if(err) throw new noData('No Data');
});
The first error throws correctly, but the second one but the second one throws a general nodejs error.
throw e; // process.nextTick error, or 'error' event on first tick
What am i doing wrong here? Is connect-mongo causing it to lose binding somehow? Any thoughts are greatly appreciated.
The problem doesn't lie in express or connect-mongo, the callback is in a different scope. To resolve this simply add a (this) to the end of the call.
//Get user from database
db.collection('users').find({}, {limit:1}).toArray(function(err, result) {
if(err) throw new noData('No Data');
}(this));
Now node knows about my custom error. (hallelujah) This essentially an iife which allows me to pass in a param.