javascript - $Http.get(), how to deal with 404 response from WebAPI - Stack Overflow

On my web application I perform a GET mand to a remote HTTP WebAPI service$http.get(url).then(function(

On my web application I perform a GET mand 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?

On my web application I perform a GET mand 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?

Share Improve this question asked Jun 1, 2016 at 9:24 Gianluca GhettiniGianluca Ghettini 11.7k24 gold badges99 silver badges168 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5
$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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742306506a4419043.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信