简化代码......但基本场景是我正在使用 Mongo 进行 findOne 查询以查找用户,但如果用户不存在,则会引发导致整个网络服务器崩溃的错误。有人能指出我正确的方向来正确包装这些错误,这样他们就不会把一切都搞砸了吗?
路线:
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");
}
});
});
DBError 声明:
function DBError(msg) {
this.name = "DBError";
console.log("DBError " + msg);
Error.call(this,msg);
Error.captureStackTrace(this, arguments.callee);
}
这是处理错误的块:
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"});
}
});
现在,当我在这里运行单元测试时是堆栈跟踪,然后结束服务器进程(不理想!):
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]