Consider this block of code:
getUser(userId)
.catch(function(error){
crashreporter.reportError('User DB failed', error);
// show user a generic error
})
.then(function(user) {
return chargeCreditCard(user);
})
.catch(function(error){
crashreporter.reportError('Credit card failed', error);
// show user an error saying that their credit card got rejected
})
Obviously, the problem with this is that the THEN(USER) block gets executed if User DB fails. Another option is to move the first catch block to the end of the chain. However, that causes another issue! We won't be able to differentiate whether the error comes from the User DB or CreditCard.
Is the following pattern, which I think solves the problem, considered a Promise Anti Pattern? Is there a better way of doing this? The problem that I see with this, is that you can end up in a semi-callback hell.
getUser(userId)
.then(function(user) {
return chargeCreditCard(user)
.catch(function(error){
crashreporter.reportError('Credit card failed', error);
// show user an error saying that their credit card got rejected
});
})
.catch(function(error){
crashreporter.reportError('User DB failed', error);
// show user a generic error
})
Edit: I guess I haven't been very clear. What if there are more THEN blocks, like what below. The problem is that once you hit one ERROR, you don't want the chain to continue at all.
getUser(userId)
.then(function(user) {
return chargeCreditCard(user);
}, function(error){
crashreporter.reportError('User DB failed', error);
// show user a error 1
})
.then(function(chargeId) {
return saveChargeId(chargeId);
}, function(error){
crashreporter.reportError('ChargeId DB failed', error);
// show user a error 2
})
.then(function(chargeHistoryId) {
return associateChargeToUsers(chargeHistoryId);
}, function(error){
crashreporter.reportError('chargeHistoryId DB failed', error);
// show user a error 3
})
.catch(function(error){
crashreporter.reportError('Credit card failed', error);
// show user a error 4
})