Search code examples
angularjsrestangular

Restangular : addResponseInterceptor not working


I am working on angularjs project.

In app.js I used addResponseInterceptor to intercept every request to the server. If there is no error (response.status == 200 OK) in response then it works perfect. But I want to intercept particularly when (response.status == 401). In this case I want to redirect user to the login page. But it's not working.

Here is my app.js addResponseInterceptor's code :

RestangularProvider.addResponseInterceptor(function(data, operation, what, url, response, deferred) {
        if (response.status === 401)
        {
            window.location = 'To the login page';
        } else
        {
            var extractedData;
            extractedData = data;
            return extractedData;
        }
    });

I got these error when request refuse to get data

enter image description here

I tried to debug the response by "console.log(response)" But It not displaying anything. It seems like if there is error in response then it not entering into thr interceptor block.


Solution

  • what you need is error-intecetpr. example below

    Restangular.setErrorInterceptor(function(response, deferred, responseHandler) {
        if(response.status === 403) {
            refreshAccesstoken().then(function() {
                // Repeat the request and then call the handlers the usual way.
                $http(response.config).then(responseHandler, deferred.reject);
                // Be aware that no request interceptors are called this way.
            });
    
            return false; // error handled
        }
    
        return true; // error not handled
    });