I am under the impression that these two things are not equivalent:
return somePromise()
.then()
.then()
.then()
.catch(function(e) { throw e; });
and
return somePromise()
.catch(function(e) { throw e; });
.then()
.catch(function(e) { throw e; });
.then()
.catch(function(e) { throw e; });
.then()
.catch(function(e) { throw e; });
The first snippet will only catch errors on the latest then (the other errors will be lost) whereas the second snippet will catch any error anywhere along the chain.
But I must be missing something because forcing the user to remember putting a catch after every promise defeats the purpose of promises.
Am I misunderstanding and placing a .catch()
last will catch any error along the chain?
In the first case, if any of the
then
handlers are throwing an error, then that error will be caught at the lastcatch
handler.In the second case, if any of the
then
handlers throw an error, that error will go to the nearestcatch
handler. As you throw the error incatch
handlers as well, it will simply go to the next nearestcatch
handler.Nope,
catch
at the end of the promise chain is the right thing to do in most of the cases. But, in case if you don't want to fail the entire chain of promises because of an intermediate failure, then you can return the value to be used by the nextthen
handler in thecatch
handler.Some samples to have a better understanding of errors with promises.
You have to run the snippet and compare the result with the code to understand what happen.
In this sample we have :
This sample try to show 4 different ways to handle the errors, and the result.
I hope this can help someone !
Just adding to thefourtheye's great answer. Here is how your two code snippets look in synchronous code:
Becomes:
The second example:
Becomes, the not very interesting: