angularJs interceptor / provider

by Dejan Vasic

JavaScript

application.config(function($provide) {
    $provide.decorator('$q', ['$delegate', '$window', function($delegate, $window) {
        var originalDefer = $delegate.defer;
        $delegate.defer = function() {
            var deferred = originalDefer();
            deferred.promise.handleQuestion = function(successFn, errorFn) {
                deferred.promise.then(successFn, function(response) {
                    if (response.statusCode === 401) {
                        // 401 for us means that the Insurance Application context no longer exists or hasn't been created yet.
                        // Due to the fact the API has been hit before the MVC controller action method
                        // So if we just reload this, then everything will get back to normality!
                        $window.location.reload();
                    } else {
                        // Let the controllers handle 500 errors
                        errorFn(response);
                    }
                });
            };
            return deferred;
        };

        return $delegate;
    }]);
});