Skip to content

Does catch block not get executed if ‘onRejected’ function is provided for ‘then’ block in a Promise?

Newbie in Promises here.

The documentation (as in the below image) tells it internally calls the onRejected function of catch block itself. So is there any use of having a catch block in a Promise if then is being provided with both the functions?

I tried throwing an error using throw 'error' and even Promise.reject('error') in the then block neither of which triggered the catch block.

Here’s the sample code.

actionPromise = Promise.reject('error')  // or throw 'Error'
actionPromise
      .then(
        (response) => next({ ...rest, response, type: SUCCESS }),
        (error) => next({ ...rest, error, type: FAILURE })  // <--- Gets triggered
      )
      .catch((error) => {
        console.error('MIDDLEWARE ERROR:', error);  // <--- Not getting triggered
        next({ ...rest, error, type: FAILURE });
      });

enter image description here

Answer

So is there any use of having a catch block in a Promise if then is being provided with both the functions?

If you provide the promise rejection handler to the then() method, then that handler will execute only if the promise, on which then() method is called on, gets rejected.

Error handler passed to the then() method is also not invoked if you throw an error from the same then() method’s fulfilment handler.

Following code snippet shows an example:

Promise.resolve(123)
.then(
  val => { throw val },
  error => console.log("inside error handler of first then")
)
.catch(error => console.log("inside catch method"));

It is different to the catch() method because catch() method will handle the promise rejection of any promise that come before it in the promise chain.

If you throw an error or return a promise that is rejected from the error handler of the then() method, only then catch() method’s callback function will be invoked.

Following code snippet shows an example:

Promise.reject(123)
.then(
  val => console.log(val),
  error => { throw eror }
)
.catch(error => console.log("inside catch method")); 

Think of the catch() method as a global error handler for all the preceding promises in the promise chain whereas the error handler for the then() method is only executed if the original promise, on which then() method is called on, gets rejected.