简体   繁体   English

触发AngularJS $ http承诺的错误条件?

[英]Triggering error condition for AngularJS $http promises?

So I have a service defined as follows: 所以我有一个服务定义如下:

angular.module('services', ['ngResource'])
    .factory('Things', function ($rootScope, $http) {
    var basePath = 'rest/things/';
    return {
        getAll: function () {
            return $http.post($rootScope.PAGES_URL + basePath + 'getAll/' + window.clientId, {});
        }
    };
});

Then, elsewhere, I'm consuming that service w/: 然后,在其他地方,我正在使用以下服务:

Things.getAll().success(function(things){
  //do something w/ things
})
.error(function(err){
  // Clearly, something went wrong w/ the request
});

What I'd like to do, is be able to "throw" the error condition if, for instance, there's a problem w/ the data at the service level. 我想做的是,例如在服务级别数据出现问题时,能够“抛出”错误情况。 ie: 即:

Data comes back as: 数据返回为:

{
  status:500,
  message:'There was a problem w/ the data for this client'
}

And so then in the service there would be something like: 因此,在服务中将出现以下内容:

getAll: function () {
        return $http.post($rootScope.PAGES_URL + basePath + 'getAll/' + window.clientId, {})
  .throwError(function(data){
    return (data.status && data.status == 200);
  });
}

So when the throwError callback returns false, the error() promise would then be called instead of the success promise. 因此,当throwError回调返回false时,将调用error()承诺而不是成功承诺。

Does anyone have any ideas on how to accomplish this? 是否有人对如何实现这一目标有任何想法?

Thanks a bunch! 谢谢一群!

If you're sure that all requests will follow the convention where the data returned from a response includes a status code, then using an HTTP Interceptor makes sense. 如果您确定所有请求都将遵循从响应返回的数据包括状态码的约定,则可以使用HTTP拦截器。 To do this, you can create a service and push it to the interceptor list for the $httpProvider : 为此,您可以创建一个服务并将其推送到$httpProvider的拦截器列表中:

.factory("myHttpInterceptor", function ($q) {
    return {
        response: function (response) {
            if (response.data.status && (response.data.status === 500)) {
                return $q.reject(response);
            }
            return response || $q.when(response);
        }
    };
});

You could replace the === 500 with something like >= 400 to handle all errors, not just a 500. 您可以将=== 500替换为>= 400以处理所有错误,而不仅仅是500。

And inside your module's .config() , add this: 在模块的.config() ,添加以下内容:

$httpProvider.interceptors.push("myHttpInterceptor");

References: 参考文献:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM