Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Throwing exception on mongoose callback

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.

Problem courtesy of: Daniel Albert

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.

Solution courtesy of: JohnnyHK

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Throwing exception on mongoose callback

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×