AngularJS $http,错误处理,拦截器和响应状态码 0

标签 angularjs error-handling

我预计错误的请求会落在 $http#error 中定义的函数中,但那并没有发生。相反,我必须创建一个拦截器。即使我知道状态码应该是 404,响应中返回的状态码是 0。

 $http({url: "myurl", method: "GET"}).success(
   function(data, status, headers, config) {
     if (data.ret_code === 200) {
        //do something
     }
   }).error(function(data, status, headers, config) {
     //NEVER GETS HERE ON BAD REQUEST!!
   });

这是拦截器:

var interceptor = ['$q', function ($q) {

  function success(response) {
    return response;
  }

  function error(response) {
    //ALWAYS 0!
    var status = response.status;

    return $q.reject(response);
  }

  return function (promise) {
    return promise.then(success, error);
  }
}];

1-这是为什么? 2-有没有办法在 $http#error 中捕获错误的请求? 3-有没有办法获取实际的 404 状态代码?

最佳答案

我知道 Android 中有一个“错误”,从浏览器缓存传送的文件给出状态码 0。

Github 问题: https://github.com/angular/angular.js/issues/1720

黑客修复(来自同一页面):

// fix status code for file protocol (it's always 0) and 0 status code for http(s) protocol on Android devices
status = (protocol == 'file') ? (response ? 200 : 404) : (response && status == 0 && window.navigator.userAgent.indexOf('Android') !== -1 ? 200 : status);

关于AngularJS $http,错误处理,拦截器和响应状态码 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24922615/

相关文章:

javascript - AngularJS 输入表单验证在模型更改时不会触发

HTML:如何使用 AngularJs 填充第一行为父行且后续行为子行的行

javascript - Angular 中独特的 ng 选项

javascript - github 项目页面资源解释为脚本,但使用 MIME 类型 text/htm 传输

python - 分段故障?我没有看到任何错误...

php - 500内部服务器错误-无错误日志

c++ - 防止错误输入

html - 如何从 div 中排除一个 css 类?

c# - C# 错误处理练习中的 throw 关键字负责什么

json - Laravel 5.1自动完成功能给Symfony fatal error