Possibly unhandled rejection in Angular 1.6

前端 未结 9 1559
轻奢々
轻奢々 2020-12-06 04:31

I have a code with AngularJS:

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

In AngularJS 1.5.

9条回答
  •  时光取名叫无心
    2020-12-06 04:45

    This information helped me to track down what (in my case) was creating the promise and not adding an error handler. I found it buried in the discussion of issue #2889 "Possibly unhandled rejection with Angular 1.5.9".

    The gist, is, patch $q to cache a stack-trace on creating promises, such that it can be retrieved when the error is triggered.

    To do it, insert this code to decorate $q somewhere near the top of your angular app:

    // Decorate the $q service when app starts
    app.decorator('$q', ["$delegate", function($delegate) {
      // Create a new promise object
      var promise = $delegate.when();
    
      // Access the `Promise` prototype (nonstandard, but works in Chrome)
      var proto = promise.__proto__;
    
      // Define a setter for `$$state` that creates a stacktrace 
      // (string) and assigns it as a property of the internal `$$state` object.
      Object.defineProperty(proto, '$$state', {
        enumerable: true,
        set: function(val) {
          val.stack = new Error().stack;
          this._$$state = val;
        },
        get: function() {
          return this._$$state;
        }
      });
    
      return $delegate;
    }]);
    

    Then search the angular code for the message "possibly unhandled rejection" and put a breakpoint on that line. When the breakpoint is reached, print out the value of toCheck.stack on the console, and you'll see something like this:

    >> toCheck.stack
    "set@http://localhost:8000/js/dual-site.js:18:19
    Promise@http://localhost:8000/js/angular.js:17008:22
    then@http://localhost:8000/js/angular.js:17016:20
    catch@http://localhost:8000/js/angular.js:17026:14
    SyncStrategy.prototype.send@http://localhost:8000/js/angular-state-machine.js:436:24
    StateMachine/this.send@http://localhost:8000/js/angular-state-machine.js:235:16
    

    The offending code is the frame calling angular's catch/then functions.

提交回复
热议问题