3

I need to handle error callback of an update operation, for this i'm using method save() like this:

$scope.save = function (params) {  
  MigParams.save(params);
};

Migparams service look like this:

angular.module('monitor').
    factory('MigParams', function ($resource) {        
        return $resource('/restful/migparams');    
});

This code works great but i need to know if an error occurs in database. I have searched in google but i didn't find this particular case. Is there a way of get this?. Thanks in advance

eflat
  • 919
  • 3
  • 13
  • 34
Aramillo
  • 3,176
  • 3
  • 24
  • 49

1 Answers1

11

From https://docs.angularjs.org/api/ngResource/service/$resource:

non-GET "class" actions: Resource.action([parameters], postData, [success], [error])

non-GET "class" instance: Resource.action([parameters], [success], [error])

$resource's save method falls into the non-GET 'class' instance category), so its error callback is the third argument.

Your code would look like:

$scope.save = function (params) {  
  MigParams.save(params, 
    function(resp, headers){
      //success callback
      console.log(resp);
    },
    function(err){
      // error callback
      console.log(err);
    });
};
Community
  • 1
  • 1
Ghan
  • 797
  • 8
  • 28
  • Thanks for answer, this worked, but i used `save` insetead `$save` and removed second parameter `{}`. – Aramillo Dec 10 '14 at 16:20
  • Ah ok, cool. I edited my answer to match what worked for you (no second {} param, and using save instead of $save) – Ghan Dec 10 '14 at 16:42
  • It still takes me in success callback on errors. What can be the reason? – Hussain Jan 01 '16 at 18:10
  • I am sending a SC_BAD_REQUEST = 400 back and angular is still using the success function instead of the error function. So same problem as Hussain is having I guess? – Silver Jul 06 '16 at 08:11
  • Read this thread: http://stackoverflow.com/questions/13080877/angularjs-service-not-invoking-error-callback-on-save-method Maybe 400 is not seen as an error in Angular. Hussain, look at what code you are returning. Also check your interceptors (again see thread for more info). – Silver Jul 06 '16 at 08:20