Angular logs error to console before raising promise.catch
Asked Answered
M

1

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?

Macy answered 23/2, 2015 at 20:22 Comment(0)
S
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.

Swanky answered 23/2, 2015 at 20:56 Comment(3)
This is the correct answer, but a decorator is preferred over overwriting the whole service. See #13595969Uropygium
But shoudln't the exception not even get to this point? Shouldn't it have been handled by the catch?Pedaiah
@DavidGrinberg The catch happens after the handling that happens in this method. That's why it shows up in the console firstMacy

© 2022 - 2024 — McMap. All rights reserved.