AngularJS: Response interceptor

by gkohen

HTML

<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
<div ng-controller="ApplicationCtrl">
    <button
        class="btn btn-success"
        ng-click="get('/echo/json/')">Log 200</button>
    <button
        class="btn btn-danger"
        ng-click="get('/echo/json/error')">Log 404</button>
</div>

CSS

body{padding:20px;}

JavaScript

angular
    .module('Application',['errorsModule'])
    .controller('ApplicationCtrl',['$scope','$http',function($scope,$http) {
        $scope.get = $http.get
    }]);

angular
    .module('errorsModule',[])
    .config(['$httpProvider',function($httpProvider) {
        $httpProvider.interceptors.push('success200Interceptor','error404Interceptor');
    }])
    .factory('error404Interceptor',['$q',function($q) {
        return {
            responseError: function(response){
                console.log('Error in response context=',response.config.url)
                return $q.reject(response);
            }
        };
    }])
    .factory('success200Interceptor',['$q',function($q) {
        return {
            response: function(response){
                console.log(response.status+' intercepted');
                return response || $q.when(response);
            }
        };
    }]);