在 angular 拦截器 responseError 中获取服务器响应

Getting server response in angular interceptor responseError

我刚刚在 angularJS 中构建了一个拦截器服务来捕获来自 API 调用的所有错误,以处理像这样的一般错误:

$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  return {
   'responseError': function(rejection) {
      alert("Something went wrong");
      return $q.reject(rejection);
    }
  };
});

工作正常,我的服务器发回错误状态 409

{
message: "Email is already being used"
success: false
token: ""
}

如何从 responseError 拦截器访问此响应?

$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  return {
   'responseError': function(rejection) {
      if(rejection.status === 409) {
          //get set the error message from rejection.message/rejection.data.message and do what you want
      }
      alert("Something went wrong");
      return $q.reject(rejection);
    }
  };
});

可以这样做

$httpProvider.interceptors.push(['$q',  function($q) {
        return {
            'request': function (config) {
               //request codes
                return config;
            },
            'responseError': function(response) {

                console.log(response);
                if(response.statusText){

                    alert(response.statusText)
                }else{
                    alert("Server down")
                }
                if(response.status === 401 || response.status === 409) {
                    //response code
                }
                return $q.reject(response);
            }

        };
}]);

})