Redirecting to error page in Angularjs

zilcuanu picture zilcuanu · Jul 8, 2014 · Viewed 34.9k times · Source

I am new to AngularJs. I have a single page app with routes configured having a controller and a view. The view get loaded inside the <ng-view></ng-view> element of the index.html page. Inside the controller I am making a http call to get the data and binding the data to the $scope. For success scenarios this works fine but if there is an error how do I plug in another view instead of the default view configured inside the angular route. PLease let me know.

Answer

Yuriy Rozhovetskiy picture Yuriy Rozhovetskiy · Jul 8, 2014

To implement common scenario for processing ajax errors you can implement custom request interceptor and redirect user to error page (or login page) according to error status:

myApp.factory('httpErrorResponseInterceptor', ['$q', '$location',
  function($q, $location) {
    return {
      response: function(responseData) {
        return responseData;
      },
      responseError: function error(response) {
        switch (response.status) {
          case 401:
            $location.path('/login');
            break;
          case 404:
            $location.path('/404');
            break;
          default:
            $location.path('/error');
        }

        return $q.reject(response);
      }
    };
  }
]);

//Http Intercpetor to check auth failures for xhr requests
myApp.config(['$httpProvider',
  function($httpProvider) {
    $httpProvider.interceptors.push('httpErrorResponseInterceptor');
  }
]);

Plunker here