
In my earlier blog I have discussed basics of Promise and brief on how we should handle errors correctly. While it covers basics, it does not talk about common questions Promise users would come across during development.
So, I spent one hour having a deep dig around error handling in Promise and had figured out the answers.
This blog is written in Q and A form and targeting those who are looking for the answers.
Q1: What will trigger catch
?
A1: catch
will be called when a promise is rejected. Typically, we reject a promise by calling reject(reason)
.
Besides, there are another three scenarios causing a promise to be rejected as well.
The first one is programmer errors.
They are bugs in the program. These are things that can always be avoided by changing the code. They can never be handled properly (since by definition the code in question is broken).
Secondly, explicitly throw
errors will achieve the same result.
Finally, it is the rejected nested promise. What I mean by this is the rejected state of nested promise bubbles up which makes the root promise rejected as well.
We can see that the whole promise asyncTask
is rejected due to rejected asyncTask2
.
To summarise, 3 ways below can lead to a rejected promise.
- Programmer errors (bugs) in promise constructor
- Throw errors
- Nested rejected promise
Q2: What area does a catch monitor?
A2: Dead simple! Just keep this in mind — catch will look over every place (then and async operations) up the promise chain but right before another catch
that is located higher.
asyncTask()
.then()
.then()
.then()
.catch() // covers promise constructor in asyncTask and 3 thenasyncTask()
.catch() // only covers promise constructor in asyncTask
.then()
.then()
.catch() // 2 then
One thing to note here is catch
also returns a new promise object that is chainable like then
.
Q3: Can I throw an error in catch?
A3: Yes, you can. Error that is thrown in the catch will be caught in the next catch.
asyncTask()
.then()
.then()
.catch(err => {throw new Error('operation failed')})
.catch(err => console.log(err)) // operation failed
Error handling in promise can be tricky. I hope those who are still unclear about error handling can benefit from this blog post.