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!
});