Angular 1.6.0: “Possibly unhandled rejection” erro

2020-01-28 02:46发布

We have a pattern for resolving promises in our Angular app that has served us well up until Angular 1.6.0:

    resource.get().$promise
        .then(function (response) {
        // do something with the response
        }, function (error) {
            // pass the error the the error service
            return errorService.handleError(error);
        });

And here is how we are triggering the error in Karma:

    resourceMock.get = function () {
        var deferred = $q.defer();
        deferred.reject(error);
        return { $promise: deferred.promise };
    };

Now, with the update to 1.6.0, Angular is suddenly complaining in our unit tests (in Karma) for rejected promises with a "Possibly unhandled rejection" error. But we are handling the rejection in the second function that calls our error service.

What exactly is Angular looking for here? How does it want us to "handle" the rejection?

11条回答
倾城 Initia
2楼-- · 2020-01-28 03:31

I have observed the same behavior during test execution. It is strange that on production code works fine and fails only on tests.

Easy solution to make your tests happy is to add catch(angular.noop) to your promise mock. In case of example above it should looks like this:

resourceMock.get = function () {
    var deferred = $q.defer();
    deferred.reject(error);
    return { $promise: deferred.promise.catch(angular.noop) };
};

查看更多
手持菜刀,她持情操
3楼-- · 2020-01-28 03:39

Try adding this code to your config. I had a similar issue once, and this workaround did the trick.

app.config(['$qProvider', function ($qProvider) {
    $qProvider.errorOnUnhandledRejections(false);
}]);
查看更多
Melony?
4楼-- · 2020-01-28 03:40

Please check the answer here:

Possibly unhandled rejection in Angular 1.6

This has been fixed with 316f60f and the fix is included in the v1.6.1 release.

查看更多
相关推荐>>
5楼-- · 2020-01-28 03:41

I was also facing the same issue after updating to Angular 1.6.7 but when I looked into the code, error was thrown for $interval.cancel(interval); for my case

My issue got resolved once I updated angular-mocks to latest version(1.7.0).

查看更多
孤傲高冷的网名
6楼-- · 2020-01-28 03:42

The first option is simply to hide an error with disabling it by configuring errorOnUnhandledRejections in $qProvider configuration as suggested Cengkuru Michael

BUT this will only switch off logging. The error itself will remain

The better solution in this case will be - handling a rejection with .catch(fn) method:

resource.get().$promise
    .then(function (response) {})
    .catch(function (err) {});

LINKS:

查看更多
登录 后发表回答