Rethrowing error in promise catch

Tags: ,



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.

Answer

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:

  1. You want to log the error, but keep the promise chain as rejected.
  2. You want to turn the error into some other error (often for easier error processing at the end of the chain). In this case, you would rethrow a different error.
  3. You want to do a bunch of processing before the promise chain continues (such as close/free resources) but you want the promise chain to stay rejected.
  4. You want a spot to place a breakpoint for the debugger at this point in the promise chain if there’s a failure.

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.



Source: stackoverflow