3

What is the best approach for having the client redirected to a error route when the API responds with a 404 when trying to load a resource given the parameters in the url, in Angular?

When someone visits for example orders/1, they see the order, but if the either don't have acces, the order is not found or any other exception is happening, how is this best handled?

Kenneth Lynne
  • 15,461
  • 12
  • 63
  • 79

2 Answers2

6

You could use an intercepter like it is suggested in this question :

Global Ajax error handler with AngularJS

When a resource request will come back from the server, it will hit the interceptor first. You can check the status of the response and react as you want.

Community
  • 1
  • 1
Galdo
  • 945
  • 6
  • 12
  • 1
    I went for this approach. Whenever the API responds with a 404 or 401, the client is redirected to the 404 page or 401 unauthorized page. Clean and simple. Thanks. – Kenneth Lynne Apr 20 '13 at 12:38
6

You can use the $routeChangeError event

$scope.$on('$routeChangeError', function(arg1, arg2, arg3, arg4){
    if(arg4.status == 404) {
        $location.url('/my-error-route');
    }
});
David Spence
  • 7,999
  • 3
  • 39
  • 63
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531