user1751287
user1751287

Reputation: 501

api get request, handle 404

I am looking into handling 404 requests from api call where I am returning html when it occours.

$http.get('/api/house/' + $routeParams.id)
   .then(function (res) {

    $scope.houses = res.data;

}, function (err) {

    //when not found I am binding html from response
    if(err.status == 404){  
        $scope.errHtml = $sce.trustAsHtml(err.data);
    }

});

returned html for 404:

<!doctype html>
<html>
<head>

   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <link rel="stylesheet" type="text/css" href="/resources/css/bootstrap.min.css">

   <title>404</title>

</head>
<body>

    <div>test 404</div>

</body>
</html>

in view I have:

<div ng-bind-html="errHtml"></div>

I am trying to understand if this is the best way to handle 404 from api call in angular js

Upvotes: 1

Views: 383

Answers (1)

Muhammed Anees
Muhammed Anees

Reputation: 1850


The best way to handle error responses in angularjs is to write an $http interceptor. Just write an interceptor service and push it to $httpProvider interceptors and then you can handle all your errors at one place.
See the Documentation here The code will look like

.factory('httpRequestInterceptor', function ($q, $location) {
    return {
        'responseError': function(rejection) {
            if(rejection.status === 404){
                $location.path('/404/');                    
             }
            return $q.reject(rejection);
         }
     };
});

Then, you can inject this service into interceptor in config block

.config( function ($httpProvider) {
    $httpProvider.interceptors.push('httpRequestInterceptor');
});


You can handle other error codes also here and redirect accordingly. Hope this will help.

Upvotes: 1

Related Questions