Throwing exception on mongoose callback
Problem
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. (/home/server/routes/api/game.js:219:17)
at Promise. (/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. (/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.
Solution
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.
Discussion
View additional discussion.