I have a chain of promises
promisedStep1()
.then(promisedStep2)
.then(promisedStep3)
.then(promisedStep4)
.then(function (value4) {
// Do something with value4
})
.catch(function (error) {
// Handle any error from all above steps
});
And I need to know at which step I got an error.
If I add catch to each promised step
promisedStep1()
.catch(function(){
throw {code: 1}
})
.then(promisedStep2)
.catch(function(){
throw {code: 2}
})
.catch(function (error) {
console.log('error in ', error.code);
});
code
would be always 2, because it goes from first catch to second.
What are the techniques in handling such errors?
Edit
Found a way:
function promisedStep1Wrapper(){
return promisedStep1()
.catch(function(){
throw {code: 1};
});
}
function promisedStep2Wrapper(){
return promisedStep2()
.catch(function(){
throw {code: 2};
});
}
promisedStep1Wrapper()
.then(promisedStep2Wrapper)
.catch(function(err){
console.log(err.code);
});
Is this ok, or is there any better solution?