Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In the Promise of Javascript, why can't the error be passed to the next chain `.catch()`?

Following is an example:

var promise = new Promise(function(resolve, reject) {
  throw new Error('test');
});
promise.catch(function(error) {
  console.log(error + ' 1 ');
  return error
}).catch(function(error) {
  console.log(error + ' 2 ');
  return error
})

The result for the codes are:

Error: test 1 

As can be seen, the second catch call doesn't work. Does that mean Promise cannot handle error using the chain syntax of catch? Is there a way to pass the current error to the next catch() call?

like image 910
Hanfei Sun Avatar asked Dec 28 '25 13:12

Hanfei Sun


2 Answers

Returning the error will not make it hit the next catch. You need to throw the error again:

promise.catch(function(error) {
  console.log(error + ' 1 ');
  throw error
}).catch(function(error) {
  console.log(error + ' 2 ');
  return error
})
-> Error: test 1 
-> Error: test 2 
like image 173
James Donnelly Avatar answered Dec 31 '25 03:12

James Donnelly


You have to throw the error again, as opposed to just returning an error object:

var promise = new Promise(function(resolve, reject) {
  throw new Error('test');
});
promise.catch(function(error) {
  console.log(error + ' 1 ');
  throw error
}).catch(function(error) {
  console.log(error + ' 2 ');
  return error
})

js has no internal notion of "this is an error object so throw it" - if there had been a then() clause following your first catch(), operation would have been deferred to that, like so:

var promise = new Promise(function(resolve, reject) {
  throw new Error('test');
});
promise.catch(function(error) {
  console.log(error + ' 1 ');
  return error
}).then(function(error) {
  console.log(error + ' 2 ');
  return error
})

Hope this helps!

like image 21
jonny Avatar answered Dec 31 '25 02:12

jonny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!