I found the following code in a tutorial:
promise.then(function(result){ //some code }).catch(function(error) { throw(error); });
I'm a bit confused: does the catch call accomplish anything? It seems to me that it doesn't have any effect, since it simply throws the same error that was caught. I base this on how a regular try/catch works.
catch " around the executor automatically catches the error and turns it into rejected promise. This happens not only in the executor function, but in its handlers as well. If we throw inside a . then handler, that means a rejected promise, so the control jumps to the nearest error handler.
In situations where you don't want this ugly thing that JavaScript displays, you can throw your error (an exception) with the use of the throw statement. This error can be a string, boolean, or object. And if there is an error, the catch statement will display the error you throw.
catch() The catch() method returns a Promise and deals with rejected cases only. It behaves the same as calling Promise.
If you throw an error inside the promise, the catch() method will catch it, not the try/catch. In this example, if any error in the promise1, promise2, or promise4, the catch() method will handle it.
There is no point to a naked catch and throw as you show. It does not do anything useful except add code and slow execution. So, if you're going to .catch()
and rethrow, there should be something you want to do in the .catch()
, otherwise you should just remove the .catch()
entirely.
The usual point for that general structure is when you want to execute something in the .catch()
such as log the error or clean up some state (like close files), but you want the promise chain to continue as rejected.
promise.then(function(result){ //some code }).catch(function(error) { // log and rethrow console.log(error); throw error; });
In a tutorial, it may be there just to show people where they can catch errors or to teach the concept of handling the error, then rethrowing it.
Some of the useful reasons for catching and rethrowing are as follows:
But, a plain catch and rethrow of the same error with no other code in the catch handler doesn't do anything useful for normal running of the code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With