Tuesday 14 March 2017

Catch connection timeout error | catch all status code for http | get query parameter and headers from http - Angular js

It is very important to capture timeout and other errors to handle the exceptions gracefully. Angular js http provides an easy way to capture all of them. Let us check with an example.

$http call

$scope.invokeApi= function()
 var url = '//sampleurl'
 $http.get( url, {cache: false} )
 .success( function( data, status, headers, config )
 .error( function( data,status,headers,config)

Here data is nothing but the api response that everybody knows. Status will give status of the request call, if it is success normally gives 200 and for timeout it will be zero in the error call back. To know status codes and meanings refer this article HTTP status codes and meanings.


headers() will give the header info of the api.


config will give header information as well as other info like below.

Get query parameter from response.

Let us check with an example how to get query parameter from response.

 Example api :
 var currentTime = new Date().getTime();
 url = 'sample/get?time='+currentTime;

We need to read query parameter from response, let us check how the code will be.

 config.url // result will be full api
 config.url.split('?time=') // depending on your requirments

If you have only one api call you can assign to a variable and take the value easily. But if you are dealing with multiple asynchronous apis then you need to capture from the response.

Catch exceptions globally | Catch all $http status.

If you want to capture exceptions globally, we need to use some interceptor. Using this you will be able to get all status code for all api either it is success or failure. And you can easily manage the exceptions.

.push(['$q', '$injector','$rootScope', function ( $q, $injector,$rootScope) {
 return function (promise) {
 return promise.then(function (response) {
  return response;
 }, function (response) {
  console.log(response); // response status
  return $q.reject(response);


Related Post

1. Angular js add class to active element

2. Add and remove active class on click Angular

3. Add a class for everything clicked - angular

1 comment :