1

I have some piece of code dealing with promises that can throw errors. I tried to make a very small example showing the problem.

In both functions g1 and g2, we call a function f, which doesn't throw errors but can set an object err with an error:

let err;

function f() {
    err = new Error('error');
    return $q.when('ok');
}

// First implementation
function g1() {
    return f().then(res => {
        if (err) {
            throw err;
        } else {
            return res;
        }
    });
}

// Second implementation
function g2() {
    const deferred = $q.defer();
    f().then(res => {
        if (err) {
            deferred.reject(err);
        } else {
            deferred.resolve(res);
        }
    });
    return deferred.promise;
}

g2().then(res => console.log(res))
    .catch(err => console.error(err));

I thought the two implementations would give the exact same result, but there is a difference. I also have an exception handler to catch all uncatched errors in my app:

angular.module('myModule').factory('$exceptionHandler', function () {
    return function (exception, cause) {
       console.error(exception);
    };
});

When calling g2, since the error is catched, the exception handler is not called. But it is the case when calling g1: I obtain a first log from the exception handler, then a second log for the catch function.

Would someone have an idea about this difference of behavior? I think the syntax used in g1 is much easier to write and read, but I also don't my errors to be thrown twice...

  • http://stackoverflow.com/questions/23324942/angularjs-promises-rethrow-caught-exceptions – raina77ow Feb 15 '17 at 13:05
  • The exact point: "Angular's $q uses a convention where thrown errors are logged regardless of being caught" – raina77ow Feb 15 '17 at 13:06
  • Thanks, I didn't find this thread. Sorry for the duplicate. – Sebastien Castiel Feb 15 '17 at 13:18
  • This behavior has been changed with AngularJS version 1.6. See [AngularJS Developer Guide - Migrating from V1.5 to V1.6 - $q](https://docs.angularjs.org/guide/migration#migrate1.5to1.6-ng-services-$q) – georgeawg Feb 15 '17 at 13:35

0 Answers0