简体   繁体   中英

$Http.get(), how to deal with 404 response from WebAPI

On my web application I perform a GET command to a remote HTTP WebAPI service

$http.get(url).then(function(data) { do_something(); });

everything works fine when the WebAPI returns some data, however the function doesn't seem to trigger when the WebAPI return a 404 error (no data to display). How can I set a callback for it?

$http.get(url).then(function(data) {
  do_something();
}, function(err) {
  // your error function
  if (err.status == 404) {
    do_something_else();
  }
});

I think for the 404 responses, best thing is to show proper not found page. In angularjs you can intercept the response with $injector service. So you can create a service which look for 404 response and show 404 page.

    angular.module('mymodule')

    .service('APIInterceptor', function( $injector) {
      return {
       'request': function(config){
           // request logic goes here.
       },
       'responseError' : function(response){
          if (response.status === 404) {
            $injector.get('$state').go('error_500');
          }
        return response;
       }
     };
    });

$http returns status code as the second argument.

$http.get(url)
  .success(function(data, status) {
      alert(status);
  })
  .error(function(data, status) {
      alert('Error with status code: ' + status); 
  });

status{number} – HTTP status code of the response.

However, if the status is an error status, such as 404, then the error block will be called

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM