我正在开发Node.js + Express。我的数据库是Mongo,我使用Mongoose连接到这个数据库。
我试图以这种方式在Mongoose查询回调中抛出异常:
game.save(function (err) {
if (err) {
throw new app.exception.EntitySaveFailed();
}
});
但是当我这样做时,节点服务器崩溃并显示这个堆栈跟踪:
[object Object]
at Promise.<anonymous> (/home/server/routes/api/game.js:219:17)
at Promise.<anonymous> (/home/server/node_modules/mongoose/node_modules/mpromise/lib/promise.js:162:8)
at Promise.EventEmitter.emit (events.js:95:17)
at Promise.emit (/home/server/node_modules/mongoose/node_modules/mpromise/lib/promise.js:79:38)
at Promise.fulfill (/home/server/node_modules/mongoose/node_modules/mpromise/lib/promise.js:92:20)
at Promise.resolve (/home/server/node_modules/mongoose/lib/promise.js:108:15)
at Promise.<anonymous> (/home/server/node_modules/mongoose/node_modules/mpromise/lib/promise.js:162:8)
at Promise.EventEmitter.emit (events.js:95:17)
at Promise.emit (/home/server/node_modules/mongoose/node_modules/mpromise/lib/promise.js:79:38)
at Promise.fulfill (/home/server/node_modules/mongoose/node_modules/mpromise/lib/promise.js:92:20)
Forever detected script exited with code: 8
Forever restarting script for 9389 time
Listening on port 3000...
当我在mongoose回调函数之外抛出异常时,一切正常。
答案 0 :(得分:1)
当你在node.js回调中抛出异常时,会转到实际调用回调的代码,而不是代码的词法范围。在这种情况下,这意味着Promise
库会收到异常并导致程序崩溃。这就是通常通过第一个回调参数而不是异常报告错误的原因。
答案 1 :(得分:1)
您可以在函数的参数中添加“next”,因此当您需要抛出异常时,您可以执行以下操作:
function saveGame(req, res, next) {
game.save(function (err) {
if (err) {
return next(new app.exception.EntitySaveFailed());
}
});
}