I have an issue with Node.js
where my MongoClient.connect()
function needs to propagate a thrown error back up to main; however, the error is getting lost and is interpreted as an uncaughtException
.
var ErrorHandler = require('./bin/lib/error.js').ErrorHandler;
//throw new ErrorHandler('Throwing something random.', 'BadRequest', 400); // <-- this works, and throws error as expected!!
// verify that user doesn't already exist.
MongoClient.connect('mongodb://localhost:27017/testdb', function(err, db){
if (err) throw new Error( err );
db.collection('users')
.findOne({'email': useremail}, function(err,doc){
throw new ErrorHandler('User already exists!', 'BadRequest', 400); // <-- this does not work, and error gets lost as an <anonymous> function error event
});
});
I'm assuming the error is getting lost because the internal callback that I'm providing to .findOne()
does not know about the ErrorHandler
function I have created to extend the core Error
class; however, I don't know how to rectify the issue and allow me to still call errors using the custom ErrorHandler()
function from the results of a mongodb
call like mongodb.open()
. Any ideas how to get the error to propagate back up through the callbacks so I can call ErrorHandler()
from the script it is "required" in?
UPDATE
The main server.js
file which is instantiating the entire server object invokes the following at the bottom to listen for other uncaughtExceptions
and SIGTERM
events:
process.on('uncaughtException', function(err){
console.error(err.stack);
n.server.close();
}).on('SIGTERM', function(){
n.server.close();
});
When the error gets lost it propagates up to here. And executes in the .on('uncaughtException',...
block which logs the entire errorstack as expected, it just doesn't get caught where I want it to get caught in my server object.
The actual console.error(err.stack)
prints the following in this instance:
BadRequest: User already exists!
at new Error (<anonymous>)
at ErrorHandler (/home/cfarmer/dev/norad/bin/lib/error.js:4:18)
at /home/cfarmer/dev/norad/routes.js:118:13
at handleCallback (/home/cfarmer/node_modules/mongodb/lib/utils.js:96:12)
at /home/cfarmer/node_modules/mongodb/lib/collection.js:1353:5
at handleCallback (/home/cfarmer/node_modules/mongodb/lib/utils.js:96:12)
at /home/cfarmer/node_modules/mongodb/lib/cursor.js:670:5
at handleCallback (/home/cfarmer/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js:154:5)
at nextFunction (/home/cfarmer/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js:675:5)
at /home/cfarmer/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js:588:7
Thanks