如何检测所有 http GET 失败

How to detect all http GET fails?

本文关键字:http GET 失败 何检测 检测      更新时间:2023-09-26

在我的应用程序中,我有一个网格,它通过HTTP承诺获取数据。 目前我可以检测到errorCallback s - 如下所示:

myDataPromise.then(function () {
    //do stuff
}, function errorCallback(response) {
        if (response.statusText === "Not Found") {
            //do stuff
        }else if(response.statusText === "Internal Server Error"){
            //do stuff
        }

但是对于SSL错误,chrome会回击"ERR::CONNECTION被拒绝",我无法像404等那样通过读取字符串来了解这一点。 我真正想要的是显示一个简单的图像/文本,说明检索数据时出现错误,无论它是什么。 因此,如果 http GET 完全失败 - 用户知道。 在我看来,这是一个相当典型的规格,但我在网上找不到太多关于它的信息。

你必须创建一个拦截器

 // register the interceptor as a service
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  return {
    // optional method
    'request': function(config) {
      // do something on success
      return config;
    },
    // optional method
   'requestError': function(rejection) {
      // do something on error
      if (canRecover(rejection)) {
        return responseOrNewPromise
      }
      return $q.reject(rejection);
    },

    // optional method
    'response': function(response) {
      // do something on success
      return response;
    },
    // optional method
   'responseError': function(rejection) {
      // do something on error
      if (canRecover(rejection)) {
        return responseOrNewPromise
      }
      return $q.reject(rejection);
    }
  };
});
$httpProvider.interceptors.push('myHttpInterceptor');

// alternatively, register the interceptor via an anonymous factory
$httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  return {
   'request': function(config) {
       // same as above
    },
    'response': function(response) {
       // same as above
    }
  };
});
拦截

器拦截所有$http流量。即使在加载模板时也是如此。