【问题标题】:AngularJS $http, error handling, interceptors and response status code 0AngularJS $http、错误处理、拦截器和响应状态码 0
【发布时间】:2015-12-19 23:57:21
【问题描述】:

我预计错误的请求会落在 $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状态码?

【问题讨论】:

  • 它攻击你的服务器了吗?

标签: angularjs error-handling


【解决方案1】:

我知道 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);

【讨论】:

【解决方案2】:

您可以将 $rootScope 传递给拦截器并像这样更新错误函数

function error(response) {
    if (response.status === 0) {
       $rootScope.errorStatus = 'No connection. Verify application is running.';
    } else if (response.status == 401) {
       $rootScope.errorStatus = 'Unauthorized';
    } else if (response.status == 405) {
       $rootScope.errorStatus = 'HTTP verb not supported [405]';
    } else if (response.status == 500) {
       $rootScope.errorStatus = 'Internal Server Error [500].';
    } else {
      $rootScope.errorStatus = JSON.parse(JSON.stringify(response.data));
    }
   return $q.reject(response);}

您可以使用 errorStatus 对象来显示您的错误详情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-03
    • 1970-01-01
    • 2022-08-16
    • 1970-01-01
    • 2016-09-20
    • 2011-05-12
    • 2018-02-05
    相关资源
    最近更新 更多