Why did we use a .catch() rather than a catch() block while handling errors
Hello guys, can someone explain why in the following code, we use a .catch outside the function body that is when the function run is being called. Why don't we use a catch block directly after the try ? If we don't use a catch block inside, then what's the need of the try, we can remove it ?
From what I have understand, this is why we might want to use a .catch() outside the function body rather than inside:
we don't want the flow inside the function to stop every time there is an error with our return promises, instead of handling each error 1 at a time, let's just handle it at an upper level, that is when we call the function
2 Replies
You pretty much got it right
If you want to handle errors locally inside the function, then it makes sense to add the catch block with the try. However, if you need some robust way of handling any errors, you are propagating the error outside.
This is because the function is
async
it is always going to return a promise. The reason why you dont handle the Exception inside the method is because you want the error to be handled outside, that is why the .catch
is written with function run
I hope you get what I am trying to sayyeah I see
ty !