I'm developing a Node.js + Express. My database is Mongo, and I'm using Mongoose to connect to this database.
I'm trying to throw an exception in a Mongoose query callback this way:
game.save(function (err) {
if (err) {
throw new app.exception.EntitySaveFailed();
}
});
but when I do it, Node server crashes and shows this stacktrace:
[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...
When I throw an exception outside a mongoose callback function, all works fine.
When you throw an exception in a node.js callback it goes to the code that actually invoked the callback, not the lexical scope of your code. In this case, that means the Promise library receives the exception and crashes your program. This is why errors are typically reported via the first callback parameter rather than exceptions.
You can add "next" to the params of the function, so when you need to throw an exception you can do something like this:
function saveGame(req, res, next) {
game.save(function (err) {
if (err) {
return next(new app.exception.EntitySaveFailed());
}
});
}