Global Ajax error handler with AngularJS

JavascriptAjaxAngularjs

Javascript Problem Overview


When my website was 100% jQuery, I used to do this:

$.ajaxSetup({
    global: true,
    error: function(xhr, status, err) {
        if (xhr.status == 401) {
           window.location = "./index.html";
        }
    }
});

to set a global handler for 401 errors. Now, I use angularjs with $resource and $http to do my (REST) requests to the server. Is there any way to similarly set a global error handler with angular?

Javascript Solutions


Solution 1 - Javascript

I'm also building a website with angular and I came across this same obstacle for global 401 handling. I ended up using http interceptor when I came across this blog post. Maybe you'll find it as helpful as I did.

"Authentication in AngularJS (or similar) based application.", espeo software

EDIT: final solution

angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives'], function ($routeProvider, $locationProvider, $httpProvider) {

	var interceptor = ['$rootScope', '$q', function (scope, $q) {

		function success(response) {
			return response;
		}

		function error(response) {
			var status = response.status;

			if (status == 401) {
				window.location = "./index.html";
                return;
			}
			// otherwise
			return $q.reject(response);

		}

		return function (promise) {
			return promise.then(success, error);
		}

	}];
	$httpProvider.responseInterceptors.push(interceptor);

Solution 2 - Javascript

Please note that responseInterceptors have been deprecated with Angular 1.1.4. Below you can find an excerpt based on the official docs, showing the new way to implement interceptors.

$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  return {
    'response': function(response) {
      // do something on success
      return response || $q.when(response);
    },
 
   'responseError': function(rejection) {
      // do something on error
      if (canRecover(rejection)) {
        return responseOrNewPromise;
      }
      return $q.reject(rejection);
    }
  };
});
 
$httpProvider.interceptors.push('myHttpInterceptor');

This is how it looks in my project using Coffeescript:

angular.module("globalErrors", ['appStateModule']).factory "myHttpInterceptor", ($q, $log, growl) ->
  response: (response) ->
    $log.debug "success with status #{response.status}"
    response || $q.when response

  responseError: (rejection) ->
    $log.debug "error with status #{rejection.status} and data: #{rejection.data['message']}"
    switch rejection.status
      when 403
        growl.addErrorMessage "You don't have the right to do this"
      when 0
        growl.addErrorMessage "No connection, internet is down?"
      else
        growl.addErrorMessage "#{rejection.data['message']}"

    # do something on error
    $q.reject rejection

.config ($provide, $httpProvider) ->
  $httpProvider.interceptors.push('myHttpInterceptor')

Solution 3 - Javascript

Create the file <script type="text/javascript" src="../js/config/httpInterceptor.js" ></script> with this content:

(function(){
  var httpInterceptor = function ($provide, $httpProvider) {
    $provide.factory('httpInterceptor', function ($q) {
      return {
        response: function (response) {
          return response || $q.when(response);
        },
        responseError: function (rejection) {
          if(rejection.status === 401) {
            // you are not autorized
          }
          return $q.reject(rejection);
        }
      };
    });
    $httpProvider.interceptors.push('httpInterceptor');
  };
  angular.module("myModule").config(httpInterceptor);
}());

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncricardolView Question on Stackoverflow
Solution 1 - JavascriptJustenView Answer on Stackoverflow
Solution 2 - JavascriptMikeRView Answer on Stackoverflow
Solution 3 - JavascriptJan-Terje SørensenView Answer on Stackoverflow