Error thrown from a mongoose-promise callback function is not caught Error thrown from a mongoose-promise callback function is not caught mongoose mongoose

Error thrown from a mongoose-promise callback function is not caught


This is Mongoose's fault for using a bad promise implementation. Promises are throw-safe so exceptions are caught (so they can be later handled by future code) - the future code never comes and Mongoose never reports that it did not. Good promise implementations do not suffer from this issue.

Your options are two:

Use a library like Bluebird:

var Promise = require("bluebird");var mongoose = Promise.promisifyAll(require("mongoose"));User.findAsync({}).then(function(data){    JSON.prase("dsa"); // not a silent failure, will show up, easy debugging});

This has the advantage of being faster than mongoose promises so there is no performance penalty. Alternatively, if you're super conservative and don't want the performance and API gains of bluebird - you can use native promises:

// Promise is the native promisePromise.resolve(User.find({}).exec()).then(function(data){    JSON.prase("dsa");});

And then, assuming you're running a modern variant of nodejs (read: io.js v 1.4.1 or upper), you can subscribe to promise rejections:

process.on("unhandledRejection", function(p, why){    console.log("FOUND ERROR!!!!", p , why);});

So exceptions are not silently suppressed.


The exec() has two promises

.then(function) .then(null , function)

try this, I think it will help

server.get('/api/test', function(req, res, next) {    User.find({}).exec()        .then(function success(users) {            console.log('SUCCESS');            typo[0] = 1; // throws a runtime error            res.json(users);        })        .then(null, function error(err) {            console.log('ERROR');            res.json({                error: err            });        });});