You can use interceptors to write global exception handler. You just need to override responseError interceptor. Here i called "openErrorModel" method defined on $rootScope to open error model with error message when ever there is error. This would be cleaner and modularized. and you can avoid duplication this way.
Sample code:
(function (global) { "use strict"; angular.module("TestAPp").factory('httpInterceptor', ["$rootScope", "$q", function ($rootScope, $q) { return { responseError: function (response) { /* Open Error model and display error */ $rootScope.openErrorModel(response); /* reject deffered object so that it'll reach error block , else it'll execute success function */ return $q.reject(response); } }; }]); }(this));
//registering interceprtor
(function (global) { "use strict"; angular.module("TestApp", []) .config([ '$httpProvider',function ($httpProvider) { /* Register the interceptor */ $httpProvider.interceptors.push('httpInterceptor'); }]); }(this));
PS: My openErrorModel definition
$rootScope.openErrorModel = function (error) { $rootScope.errorMessage = error.data; $('#errorModal').modal('show'); };
You can refer to Error Handling in angular for more info.
$http undefined erroris that you are returning nothing to the responseError function. Return a value to that function. Better yet, return the rejection for chaining.