6

I feel like I am going a little crazy, but Angular appears to throw an error for a promise even if I have a catch defined. It throws the error to the console, then allows the catch to run.

Here is a super-simple fiddle

The test code:

$q.when(1)
    .then(function() {
        throw new Error("test");
    }).catch(function(error) {
        console.log('error caught', error);
    });

The resulting console

enter image description here (dirty liar!)

Here is a fiddle showing what I expect to happen: the catch is raised, and no other error is logged to the console. Did I fail to configure something, or does Angular implement a broken promise spec?

Kyeotic
  • 19,697
  • 10
  • 71
  • 128

1 Answers1

7

angular by default logs all errors to console.

angular also provides a way to override this behavior. $exceptionHandler is a global service that is given a chance to process any exceptions ($http, errors during $digest, etc).

If you add this piece of code:

myApp.factory('$exceptionHandler', function() {
  return function(exception, cause) {
    exception.message += ' (caused by "' + cause + '")';
    //throw exception;
  };
});

Then all errors would just stop further logging. Would process catch() handlers though. Updated fiddle: http://jsfiddle.net/5jjx5rn3/

UPDATE:

As pointed by dnc253 in the comments, there's a better way if you intend to actually override an angularjs service. Even not being the focus of this question, it's better to know that simply declaring a service with the same name, in whatever module, the service is fully replaced (last-in wins). If one wants to add functionality around the original service, a decorator is the right choice.

André Werlang
  • 5,839
  • 1
  • 35
  • 49
  • This is the correct answer, but a decorator is preferred over overwriting the whole service. See http://stackoverflow.com/questions/13595469/how-to-override-exceptionhandler-implementation – dnc253 Feb 23 '15 at 21:09
  • But shoudln't the exception not even get to this point? Shouldn't it have been handled by the `catch`? – David says Reinstate Monica Feb 23 '15 at 21:28
  • @DavidGrinberg The `catch` happens after the handling that happens in this method. That's why it shows up in the console first – Kyeotic Feb 23 '15 at 21:30