Monday 29 February 2016

Error Handling and authentication with Interceptors in angular

About:

             Interceptors are basically service factory which we register with $httpProvider. They are used to intercept $http requests before server call or after server returned the response, so that we can process the config object, request and responses of the $http calls and modify them according to our neeeds. These are mostly used in Global Error Handling and Authentication of the requests.

There is 4 interceptors available:

  • request: This method is called before server request is made with "config" object. We can modify config object
  • requestError: This will call if the request can't be sent to the server or interceptor rejects the request.
  • response: This interceptor will be called after server returns response. arguments contains the response object, we can modify the response.
  • responseError: This interceptor will be called if the server returns error. or request is rejected by the interceptor.

Sample script for interceptors:


Creating a service with interceptor definitions:

Here is a service which defines 2 interceptors.
  1. In request interceptor we are checking the authorization and if not authorized rejecting the request.
  2. In responseError interceptor we are calling a function defined on $rootScope , which will open error model on the UI.


Registering httpInterceptor service with $httpProvider service:

We need to register our Interceptor service with $httpProvider, so that our interceptors called on every $http calls. we just need to push our service to $httpProvider.interceptors array.


We are done! It'll call our interceptor on every $http call. 

Uses:

  1. Global error handling of the application. We don't need to write error logic for every $http request
  2. Global Authentication handling. We don't need write authorization logic before every request
   Please feel free to comment if you need any information.


No comments:

Post a Comment