Watt Watt - 3 months ago 6
Javascript Question

How to handle factory service errors in AngularJS

Factory code

app.factory('abcFactory', function ($http, Config, $log) {
var serviceURL = Config.baseURL + '/results';
return{
results:function() {
var promise = $http({
method: 'GET',
url: serviceURL,
timeout: Config.httpTimeout
}).then(function(response) {
return response;

}, function(reason) {
$log.error("Request Failed: ", reason)
});

return promise;
}
}
});


Controller code

app.controller('abcController',function ($scope, $log,abcFactory, Config)
{

abcFactory.results(function(data){
$scope.results =data;
},function(response)
{
console.log("response"+response);

if(response.status === 0)
{
console.log("gotcha");
$scope.serviceTimedoutError(response.data, response.status, response.config);
} else
{
console.log("gotcha");
$scope.serviceFailure(response.data, response.status, response.config);
}


});
});


$scope.results
populates fine when service has returned good response.

And, when there is an error I can see on console the error message coming from factory code's log saying
"Request Failed: blah blah "
.

My issue:
When there is an error, why I am not seeing error message in controller, it is not even printing
"gotcha"
in browser console. I need error details in controller, so that I can show it on view. I don't want to pass
$scope
in factory.

What wrong I am doing in Controller code?

If I am not wrong, I am doing something in line of AngularJS Failed Resource GET
but not getting desired result.

Answer

It looks like you want the results function to take callbacks, but its arguments list is currently empty. You are returning the promis though.

So either change the call in the controller to:

abcFactory.results()
  .success(function() { ... })
  .error(function() { ... })

Or change the results function itself:

results: function(successCallback, errorCallback) {
  var promise = $http(...).success(successCallback).error(errorCallback);
  return promise;
}
Comments