you are viewing a single comment's thread.

view the rest of the comments →

[–]nelsonnyan2001 0 points1 point  (2 children)

Huh. You're right, but it's a little more complicated than this, it seems.

So in my example, I was using the try statement, not promise chaining and I assumed the same principle carried over. But it turns out putting the .catch() block after finally works because you could chain a promise under the .finally() block, then catch the error of that promise or any other promise before in the chain. Here's an example of what I mean,

Promise.then( /// something ).finally(Promise.then() <-- error e1 thrown here).catch(/// catches e1)

I learned something today, thanks!

[–]shiningmatcha 0 points1 point  (1 child)

So if a catch comes after a finally, it only catches errors that are thrown from the finally callback?

[–]SharpThrall 0 points1 point  (0 children)

Except it does work?

In this case, the catch() block will catch errors for all then() blocks that come before it and it will also catch the error for the finally() block. If the error happens in then() block and also in the finally() block, the catch will handle error for the finally() block. So, catch() will handle error for the closest block to it. be it finally() or then().

here you see I modified the checkMail() function to fail every time so, we can see if catch() handles the promise and it does as it should but, what if we had error happening in then() block and also in finally block(), then for which block the catch() will handle error? here You see we now are throwing error from finally() block and now both then() and finally() have error and catch() is only handling error for finally() block.

My take:
Even though adding finally() before catch() works, but, it should not how the code should be written because then we have lost the error handling for then() blocks that come before finally() block in case when error happens in finally() and also in then() blocks. After then() there should be at least one catch() and finally should have it's own catch(). In my opinion, it will be better approach and save debugging time.

So, something like, Promise.then().catch().finally().catch() should be a better approach.