1

so in this plnkr I demonstrate a failing $http request.

The responsibility of the service is to deconstruct the server response and to ready the information for the controller to consume.

When it errors, I feel like I need to propagate the error to the controller not for handling but for being able to inform the user that the operation couldn't complete. (handling in a sense of logging etc.)

As it stands:

return $http.get('notgoing')
  .then(
    function success(result) {
      return result.data;
    },
    function error(err) {
      console.warn(err); // do something meaningful with the error

      return err;
    }
  );

this will rollup the error or success into the chained promise's success function. This isn't ideal for informing the user.

Is there a simple way to get the error function to bubble the value as an error to the next chained promise's error function. (bearing in mind I don't really want to take a dependency on the $q library and have another promise interwoven with the $http promise)

- OR -

Does the responsibility of handling that error stop at the service.

sdgluck
  • 24,894
  • 8
  • 75
  • 90
Callum Linington
  • 14,213
  • 12
  • 75
  • 154
  • 1
    Just a little addon: This [SO answer](http://stackoverflow.com/a/28703407/2375913) explains the difference between using `throw` and `reject`. – muenchdo Sep 29 '15 at 13:14

2 Answers2

3

Instead of return err;, throw it with throw err;. $q will handle the "uncaught" error and reject the chain.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
0

I don't think there is a way without using $q, but Angular brings its own implementation along, so all you need to do is to inject it into your service and then call $q.reject(err). Otherwise Angular will think your error has already been handled inside the service.

angular.module('test', []).factory('testService', function ($http, $q) {
  ...  
  function test() {
    return $http.get('notgoing').then(function success(result) {
      return result.data;
    }, function error(err) {
      console.warn(err);
      return $q.reject(err);
    });
  }
});

Check the updated Plunker.

muenchdo
  • 2,161
  • 1
  • 17
  • 30