Possibly unhandled rejection in Angular 1.6

2019-01-25 02:31发布

I have a code with AngularJS:

service.doSomething()
  .then(function(result) {
      //do something with the result
  });

In AngularJS 1.5.9 when I have error in the .then() section like:

service.doSomething()
  .then(function(result) {
      var x = null;
      var y = x.y;
      //do something with the result
  });

I'm getting clear error message:

TypeError: Cannot read property 'y' of null

But in version 1.6 with the same code I'm getting a different error:

Possibly unhandled rejection: {} undefined

I know that this is related to this change, and the single solution is quite simple by adding .catch() block:

service.doSomething()
  .then(function(result) {
      var x = null;
      var y = x.y;
      //do something with the result
  })
  .catch(console.error);

Now I again have what I want:

TypeError: Cannot read property 'y' of null

But how to obtain the same result (more detailed error) for entire application without adding .catch() block in every single place?

I tested the suggested solution to disable this by adding:

$qProvider.errorOnUnhandledRejections(false);

But with this the situation is even worse - I do not have ANYTHING in the console! The error is swallowed somewhere and not logged at all. I'm not sure is it a problem with AngularJS 1.6 or with my configuration.

Do you have any ideas how to "restore" logging behavior from version 1.5.9?

EDIT:

Adding custom error handler:

.factory('$exceptionHandler', function($log) {
  return function(exception, cause) {
    $log.warn(exception, cause);
  };
})

does not help at all. In the error handler I already receive the "wrapped" error.

9条回答
smile是对你的礼貌
2楼-- · 2019-01-25 02:55

errorOnUnhandledRejections(false); was not a resolution for me.

You do indeed need to define an exception handler... however... wrap it in a timeout function: this will force the original exception/stack trace to be thrown.

To make the error show up as an error in the web console, as you originally intended:

ng.factory('$exceptionHandler', function($log) {
  return function(exception, cause) {
    // do some some stuff...
    setTimeout(function(){
      // throw the original exception (with correct line #'s etc)
      throw exception;
    })
  };
});

Heres the timeout trick: Why can I not throw inside a Promise.catch handler?

查看更多
Rolldiameter
3楼-- · 2019-01-25 03:00
不美不萌又怎样
4楼-- · 2019-01-25 03:03

I fixed the same problem with version 1.6.1 by upgrading angular-ui-router to 0.3.2.

查看更多
登录 后发表回答