Search code examples
angularjsangularjs-directiveangularjs-service

Display custom error page in angular js


I can try to make custom error page in angular js means that when 404 error occurred then display 404.html page and when 500 error occurred then display 500.html page like so on so please tell me how can i make this..??


Solution

  • You can handle this with a request interceptor. You didn't provide us with what you use for routing so you'll have to insert your code to route to a 404 page and a 500 page.

    The factory will look like this:

    angular.module("app").factory('sessionInterceptor', [factory]);
    function factory() {
        var requestInterceptor = {
            response: function(response) {
                // Code you want for successful responses here
                return response;
            },
            responseError: function(rejection) {
                if (rejection.status === 404) {
                    // 404 code here
                }
                return rejection;
            }
        };
    
        return requestInterceptor;
    }
    

    Then you need to add the interceptor in a config block to the $httpProvider:

    .config(['$httpProvider', function($httpProvider) {
        $httpProvider.interceptors.push('sessionInterceptor');
    }])
    

    All network requests using $http will now pass through the request interceptor.