Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to throw an error in a $http promise

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

My question is how do I throw an error so that a promise that triggers the .error method gets called? I don't want to just throw error since I want it to use the .success/.error in the calling function rather than doing a try catch 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
   }
like image 559
MonkeyBonkey Avatar asked Mar 17 '23 23:03

MonkeyBonkey


1 Answers

You don't need $q.defer(). And else too. You can use reject directly:

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

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

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

like image 61
Anton Bessonov Avatar answered Apr 01 '23 22:04

Anton Bessonov