5

I have the following piece of code:

var myFunc = function(id, obj, backupObj) {
  return update(obj) // this returns a promise
  .fail(function(err){
    // if update is rejected
    restore(id, backupObj); // i wish to run this
    // and return the error that 'update(obj)' threw and propagate it
    return Q.reject(err); // should it be thrown like this???
  });
}

Is this the correct way to handle the failure of update() and return the error, so when myFunc() is called from any place it can be propagated and finally handled? For example, being executed inside a chain:

var foo = function(id, obj) {
  var backupObj = {};

  return checkIfValidObj(obj)
  .then(function(_backupObj) {
    backupObj = _backupObj;
    return doSomethingElse(id, obj);
  })
  .then(function() {
    // here!
    return myFunc(id, obj, backupObj);
  });
}

And then, as the foo caller, I would like to do some error handling and be able to catch the error that update(obj).fail() might return:

foo()
.then(function() { /* everything worked as expected, so we are happy */ })
.catch(function(err){ 
   // I want this to be executed also if 'update(obj)' inside 'myFunc' was rejected!
});
charliebrownie
  • 5,777
  • 10
  • 35
  • 55
  • 1
    Yes, both `throw err;` as well as `return Q.reject(err);` (they're equivalent) are the correct way to handle this. – Bergi Nov 27 '15 at 12:07
  • @Bergi's link answers the question for Q, not just Dojo, because this is covered by [The Promises/A+ spec](https://promisesaplus.com/#point-42), so will be true of any A+-style promise lib. – T.J. Crowder Nov 27 '15 at 12:13

0 Answers0