Proper error handling in Promises
The standard way of catching errors in promises is to use .catch(onError)
. The onError
handler runs if the previous promise is rejected.
But you can handle rejections using the second parameter of the then
call too. A common source of confusion is that these two are not equivalent:
.then(onSuccess).catch(onError)
vs
.then(onSuccess, onError)
In the second case, rejections in onSuccess
are not handled by onError
.
Why is that?
The source of confusion is that rejection handling is somewhat similar to the try-catch structure. But unlike the try-catch where everything written before the catch is protected, promises work in steps. And rejections are handled in the next step.
Under the hood, catch(onError)
is just a shorthand for .then(undefined, onError)
.
In the example above, the catch-ed version translates to:
.then(onSuccess).then(undefined, onError)
Which defines a separate step to handle rejections, while the .then(onSuccess, onError)
defines both handlers in a single step.