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

3

我本以为错误请求会在$ 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状态码?


它是否正在访问您的服务器? - V31
2个回答

1
我知道Android中存在一个“bug”,即从浏览器缓存中提供的文件会给出状态码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);

1
这就是为什么状态码为-1的原因。 - Renan Franca

0

你可以将$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对象来显示您的错误详情。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接