Watt Watt - 6 months ago 17
Javascript Question

How to handle factory service errors in AngularJS

Factory code

app.factory('abcFactory', function ($http, Config, $log) {
var serviceURL = Config.baseURL + '/results';
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)

$scope.results =data;

if(response.status === 0)
$scope.serviceTimedoutError(response.data, response.status, response.config);
} else
$scope.serviceFailure(response.data, response.status, response.config);


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
in browser console. I need error details in controller, so that I can show it on view. I don't want to pass
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.


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:

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

Or change the results function itself:

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