Restangular error handling issue

Issue

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

Solution

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

Answered By – Patrick Refondini

Answer Checked By – Terry (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.