user526206
user526206

Reputation:

How to get error from http service

I am trying to get http error if service failed to load a url. I have created a angular factory which is like this:

  loadUsers: function () {
        return $http.get(urlService.url("/users"));
    },

in controller i try to using this factory method to load ruserlist:

  urlservice.loadUsers()
            .then(function(response) {
                 $log.info("user loaded");
            })
          .finally(data.bind(undefined, result));

at this point i want to handle http error but not getting idea where i have to use error function as this is returning a promise. Can someone give me hint.

Upvotes: 0

Views: 62

Answers (4)

Sachet Gupta
Sachet Gupta

Reputation: 837

 urlservice.loadUsers().then(successCallback, errorCallback)
     .finally(data.bind(undefined, result));

 var successCallback = function(response) {
     // handle data recieved
     $log.info("user loaded");
 };

 // create generic method for handling service errors
 var errorCallback = function(error) {
     // handle error here
     $log.info("error occurred");
 };

Upvotes: 0

Sachila Ranawaka
Sachila Ranawaka

Reputation: 41387

Just add another function inside promise like this

 urlservice.loadUsers()
            .then(function(response) {
                 $log.info("user loaded");
            },function(response) {
                 $log.info("error");
            })
          .finally(data.bind(undefined, result));

Upvotes: 0

Karim
Karim

Reputation: 8632

add a second callback to the .thenmethod, that will be triggered in case of error.

from the angular doc: https://docs.angularjs.org/api/ng/service/$http

$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

Upvotes: 1

Paul
Paul

Reputation: 36319

Just add a .catch to your promise:

urlservice.loadUsers()
            .then(function(response) {
                 $log.info("user loaded");
            })
          .catch(function(err) {
             console.log(err);
          })
          .finally(data.bind(undefined, result));

Upvotes: 1

Related Questions