Restangular error handling issue

sbouba picture sbouba · Mar 11, 2014 · Viewed 12.1k times · Source

I'm having an issue with restangular. This code :

Restangular.one("undefined_ressource").get().then(
    function(res){
        console.log("success", res.code);
    },
    function (res) {
        console.log("fail", res.code);
   }
);

Tries to get the url http://api.local.com/undefined_ressource which does not exits. My server returns a 404, as expected, but the fail log is never fired. Intead it goes in the success callback and logs "success 404" to the console.

Angular version 1.2.15
Restangular version 1.3.1

Any help would be welcomed! Thanks

Answer

Patrick Refondini picture Patrick Refondini · Mar 14, 2014

Adapted from your code example

Restangular.one("undefined_ressource").get().then(
    function(myObject){
        console.log("success obtained myObject");
    },
    function (res) {
        console.log("fail", res.status);
   }
);
  • If Restangular call is successful:

then first function should be invoked and its argument should be myObject. Unless your myObject has a specific code or status field, there won't be any added by Restangular.

  • If Restangular call fails:

then second function should be invoked and its argument be a response object with status, header, data, config fields. There shouldn't be any code field available as shown in your example.

In case of an HTTP 404 Not Found exception, in my navigator javascript console I do obtain: "fail" 404

With error interceptor

myAngularApp.run(['Restangular', '$window', function(Restangular, $window){
    Restangular.setErrorInterceptor(
        function(response) {
            if (response.status == 401) {
                console.log("Login required... ");
                $window.location.href='/login';
            } else if (response.status == 404) {
                console.log("Resource not available...");
            } else {
                console.log("Response received with HTTP error code: " + response.status );
            }
            return false; // stop the promise chain
        }
    );
}]);

If an error interceptor is set up on your angular application myAngularApp as in the above example, the failure should no more reach your custom call then second function but be processed by the errorInterceptor set up function.

In case of an HTTP 404 Not Found exception, in my navigator javascript console I do obtain: Resource not available...

Tested with:

Angular version 1.2.14
Restangular version 1.3.1