Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper error handling in mongoose query.exec()

I've digged into Mongoose docs, but I still can't find the information how I should handle errors in query.exec().

var query = User.findOne({_id: userId});

    var promise = query.exec(function(err) {
        if (err) {
            res.json(err);
            return;
        }
    });
    promise.then(function(user) {
        res.json(user.name);
    });

When I pass incorrect userId, I'm getting Unhandled rejection CastError: Cast to ObjectId failed error printed to the console.

I thought that res.json(err) followed by return statement will be enough to handle the error correctly and prevent it from being shown in the console, but it's not. What should I do instead?

like image 236
CorrieSparrow Avatar asked Jan 27 '17 14:01

CorrieSparrow


2 Answers

With callback:

var query = User.findOne({_id: userId});
query.exec(function (err) {
    if (err) {
        // handle error
        return;
    }
    // handle success
});

With promise:

var query = User.findOne({_id: userId});
query.exec().then(function () {
    // handle success
}).catch(function (err) {
    // handle error
});

Currently you are mixing both of those styles. Choose one style and stick to it instead.

like image 122
rsp Avatar answered Sep 26 '22 17:09

rsp


With minimal change to your code:

var query = User.findOne({_id: userId});

    var promise = query.exec(function(err) {
        if (err) {
            res.json(err);
            return Promise.reject(err); // Updated this line
        }
    });
    promise.then(function(user) {
        res.json(user.name);
    });

Using promises properly:

User.findOne({_.id: userId})
  .then(function(user) {
    return res.json(user.name);
  })
  .catch(function(err) {
    return res.json(err);
  });
like image 29
Sangharsh Avatar answered Sep 24 '22 17:09

Sangharsh