0

I am using interceptor in my app for generic error handling when service is down I am getting success response with status 200 even i have changed the base url to test my service. What am i doing wrong??

 var myServices = angular.module('myServices', ['ngResource']); myServices.config(function ($provide, $httpProvider) { $provide.factory('ErrorInterceptor', function ($q) { return { response: function(){ return response;// always success?? } responseError: function(rejection) { $scope.addErrorAlert("Services are currently not responding. Please try again later.",true); return; } }; }); 
1
  • The reason you are getting $http undefined error is that you are returning nothing to the responseError function. Return a value to that function. Better yet, return the rejection for chaining. Commented Jan 27, 2016 at 5:46

2 Answers 2

1

the best way to add interceptor in $httpProvider is to create a separate factory for that and push the same into $httpProvider.interceptors

var myServices = angular.module('myServices', ['ngResource']); myServices.factory('ErrorInterceptor', function ($q) { return { responseError: function (response) { return $q.reject(response); } }; }) myServices.config(function ($httpProvider) { $httpProvider.interceptors.push('ErrorInterceptor'); }); 
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.