Search code examples
angularjsrestangular

Restangular: Make request fail when 200 OK response contains specific payload


I have URL I'm using that gives a 200 OK status and a JSON payload of {error: "Invalid user"} when you do not provide a correct user on a GET request. When using this URL with Restangular, I would prefer this resulted in an error so I can handle errors in the typical way with promises, otherwise my code is going to be very messy. How would I do this?


Solution

  • You can specify an an response interceptor like this:

    app.config(function(RestangularProvider) {
    
        // add a response intereceptor
        RestangularProvider.addResponseInterceptor(function(data, operation, what, url, response, deferred) {
        // check the response if it contains error or not.
          if (typeof(response.error) !== 'undefined') {
                alert('Your authentication Fail!');
                return false;
            };
          return response;
        });
    
    });