How to make a mistake in the promise of $ http

I have an angular service that wraps my api calls to rest and returns the promise of $ http.

My question is: how can I make a mistake to cause a call that calls the .error method? I don’t want to just throw an error, because I want it to use .success / .error in the calling function, and not run the catch try block around it.

myFunction: function(foo)
   if (foo) {
      return $http.put(rootUrl + '/bar', {foo: foo});
   }
   else {
      //what do I return here to trigger the .error promise in the calling function
   }
+4
source share
4 answers

First enter q-service in your service. Then in your friend:

else {
     var deferred = $q.defer();
     deferred.reject("reject reason, foo was false");
     return deferred.promise;
}

Not as smart as Blazemonger, but quick to make.

0
source

You do not need $q.defer(). And so elsetoo. You can directly use the deviation:

myFunction: function(foo) {
    if (foo) {
        return $http.put(rootUrl + '/bar', {foo: foo});
    }

    return $q.reject("reject reason");
}

. https://docs.angularjs.org/api/ng/service/ $q # reject

+5

You want to create your own promise with$q . Here's how I did something similar in a recent project:

app.service('allData', ['$http','$q',function($http,$q) {
    return {
        getJson: function() {
            return $q(function(resolve, reject) { // return a promise
                $http.get('/path/to/data.json', {cache:true})
                    .success(function(data) {
                        if (angular.isArray(data)) { // should be an ordered array
                        // or any other test you like that proves it valid
                            resolve(data);
                        } else {
                            reject("Invalid JSON returned");
                            console.log(data);
                        };
                    })
                    .error(function(data) {
                        reject("Invalid data returned");
                        console.log(data);
                    });
            });
        }
    };
}]);

And in my controller:

allData.getJson().then(function(json) {
    // success, do something with the json
}, function(reason) { // failure, .getJson() had some kind of error
    alert('Sorry, unable to retrieve data from the server.')
    console.error(reason);
});
+1
source

You can raise or throw a custom error using throw new Error ("custom error").

For http:

http.get('url').toPromise().then (result =>{
  throw new Error ("My Custom Error") // New Custom error  New is optional w
}).catch(err => {
  throw  err
}); // catch will catch any error occur while http call 
0
source

All Articles