Veselin Kontić
Veselin Kontić

Reputation: 1858

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
});

Upvotes: 0

Views: 81

Answers (1)

deceze
deceze

Reputation: 522101

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.

Upvotes: 1

Related Questions