简体   繁体   中英

What is the best way to catch error on promise and why?

I have two code examples for catching promise error. What is better way and why is that so?

I have this code with .catch()

Message.receive($scope.reference).then(function (response) {
  // on success
}).catch(function (error) {
  // on error
});

Also I have this code, without .catch()

Message.receive($scope.reference).then(function (response) {
   // on success
}, function (error) {
   // on error
});

foo.then(success, error) executes one or the other callback based on whether foo raised an error or not. If success raises an error, you'll get an uncaught error, unless you chain another .catch .

foo.then(success).catch(error) catches any error raised by foo or success . If foo raises an error, success is skipped.

It's not which is better, it depends on what error handling chain you want to establish.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM