AngularJS HTTP Interceptor Generic httpInterceptor step by step


Create an HTML file with the following content:

<!DOCTYPE html>
  <title>Angular Interceptor Sample</title>
  <script src=""></script>
  <script src="app.js"></script>
  <script src="appController.js"></script>
  <script src="genericInterceptor.js"></script>
<body ng-app="interceptorApp">
    <div ng-controller="appController as vm">
        <button ng-click="vm.sendRequest()">Send a request</button>

Add a JavaScript file called 'app.js':

var interceptorApp = angular.module('interceptorApp', []);

interceptorApp.config(function($httpProvider) {

Add another one called 'appController.js':

(function() {
    'use strict';

    function appController($http) {
        var vm = this;

        vm.sendRequest = function(){

    angular.module('interceptorApp').controller('appController',['$http', appController]);

And finally the file containing the interceptor itself 'genericInterceptor.js':

(function() {
    "use strict";

    function genericInterceptor($q) {
        this.responseError = function (response) {
            return $q.reject(response);

        this.requestError = function(request){
            if (canRecover(rejection)) {
                return responseOrNewPromise
            return $q.reject(rejection);

        this.response = function(response){
            return response;

        this.request = function(config){
            return config;

    angular.module('interceptorApp').service('genericInterceptor', genericInterceptor);

The 'genericInterceptor' cover the possible functions which we can override adding extra behavior to our application.