Randomblue
Randomblue

Reputation: 116283

Unified error catching with Mongoose

I am using Mongoose. For each database operation, I have code to post the error, if any. For example:

User.find({}, function(error, users) {
    if(error) { console.error('ERROR: ', error); } else {
        // Do stuff
    }
});

Is there a way to abstract away in a single function the following boilerplate code:

if(error) { console.error('ERROR: ', error); } else {

?

Upvotes: 2

Views: 314

Answers (1)

hunterloftis
hunterloftis

Reputation: 13799

Have you considered something like this? (written freehand so check for syntax)

function safely(callback) {
  return function(err) {
    if (err) {
      console.error('ERROR: ', err);
      return;
    }
    callback.apply(this, arguments);
  };
}

User.find({}, safely(function(err, users) {
  // Do something
}));

Upvotes: 4

Related Questions