Simplified code... but the basic scenario is I'm doing a findOne query with Mongo to lookup a user, but if the user doesn't exist it throws an error that crashes the entire webserver. Can someone point me in the right direction for correctly wrapping these errors so they don't bring everything down?
The Route:
server.get('/v1/user/:token', function(req,res){
console.log("user endpoint hit");
var user = users.findOne({token:req.params.token}, function(err,user){
if (user) {
res.json({token:user.token,credits:user.credits,subscribed:user.subscribed,searches:user.searches});
} else {
console.log("DB error in lookup user");
throw new DBError("Error looking up user in get endpoint");
}
});
});
The DBError declaration:
function DBError(msg) {
this.name = "DBError";
console.log("DBError " + msg);
Error.call(this,msg);
Error.captureStackTrace(this, arguments.callee);
}
And here is the chunk that handles errors:
server.error(function(err, req, res, next){
if (err instanceof NotFound) {
res.send(404,{error: "404 Not Found"});
}
else if (err instanceof DBError) {
res.send(400, {error: "Database error"});
} else {
res.send(500,{error:"500 internal error"});
}
});
Now when I run my unit tests here is the stacktrace, which then ends the server process (not ideal!):
user endpoint hit
DB error in lookup user
DBError Error looking up user in get endpoint
/Users/msencenb/Development/nodeProjects/reversePhoneLookup/server/app/node_modules/mongodb/lib/mongodb/connection/server.js:563
throw err;
^
[object Object]