1

Please see the demo here

function get(url) {
        return $http.get(url)
          .then(function(d){ 
            return d.data
          },
          function(err){  //will work without handling error here, but I need to do some processing here
            //call gets here
            //do some processing
            return err
          })
      }

      get('http://ip.jsontest.co')
      .then(function(response){
        $scope.response = "SUCCESS --" + JSON.stringify(response);
      }, function(err){
        $scope.response = "ERROR -- " + err;
      })

I have a library function, get, which returns a promise. I am processing the error there, and returns it (where I commented //do some processing ). I was expecting in the client, it calls the error/fail handler. instead it prints "SUCCESS --" + error

I can make this work with $q and reject, but is there a way without?

bsr
  • 57,282
  • 86
  • 216
  • 316
  • possible duplicate of [Chained promises not passing on rejection](http://stackoverflow.com/q/16371129/1048572) – Bergi Nov 02 '15 at 21:49

2 Answers2

0

Replace return err with $q.reject(err), you need to inject $q of course.

In promise chaining, if you want to pass the error down, you'll need to return a rejected promise from current error handler. Otherwise, if the return value is an immediate value or resolved promise, the error is considered to be handled, so later error handlers down the chain won't be called.

Ye Liu
  • 8,946
  • 1
  • 38
  • 34
0

Generally:

  • Whenever you return from a promise handler, you are resolving indicating normal flow continuation.
  • Whenever you throw at a promise handler, you are rejecting indication exceptional flow.

In a synchronous scenario your code is:

function get(url){
    try{
       return $http.get(url);
    } catch(err){
        //handle err
    }
}

If you want to pass it further, you need to rethrow:

function get(url){
    try{
       return $http.get(url);
    } catch(err){
        //handle err
        throw err;
    }
}

Promises are exactly like that:

function get(url){
    return $http.get(url)
      .then(function(d){ 
        return d.data
      },
      function(err){  //will work without handling error here
        //call gets here
        //do some processing
        throw err; // note the throw
      })
  };

Or with even niftier syntax:

function get(url){
     return $http.get(url).catch(function(err){
           // do some processing
           throw err;
     });
}
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504