从'response'拒绝'responseError'

时间:2014-02-14 11:29:05

标签: angularjs angular-http angular-http-interceptors

有时,即使出现错误,我正在使用的API也将返回200 ok。响应JSON对象将类似于:

{
    error: true
}

我已经构建了一个$ http response拦截器,只是检查这个错误并拒绝它。我希望它然后跳转到我的responseError函数:

$httpProvider.interceptors.push(function($q) {
    return {

        response: function (response) {

            if (response.data.error) {

                // There has been an error, reject this response
                return $q.reject(response);
            }

            return response;
        },

        responseError: function(rejection) {

            // Display an error message to the user
            ...

            return $q.reject(rejection);
        }
    }
});

问题是,即使拒绝回复,我的responseError函数也不会被调用。它被称为500错误等,所以我知道它正在工作。我希望拒绝做同样的事情。

来自docs

responseError: interceptor gets called when a previous interceptor threw an error or resolved with a rejection.

关于缺少什么的任何想法?

3 个答案:

答案 0 :(得分:7)

看起来这是不可能的。要减少重复的代码,只需单独声明错误处理函数并在response和responseError函数中重用它。

$httpProvider.interceptors.push(function($q) {

    var handleError = function (rejection) { ... }

    return {

        response: function (response) {

            if (response.data.error) {
                return handleError(response);
            }

            return response;
        },

        responseError: handleError
    }
});

答案 1 :(得分:2)

添加到这个答案:在响应拦截器中拒绝承诺做了一些事情。

虽然人们会期望它在第一眼就调用responseError,但这没有多大意义:请求是通过成功完成的。 但是在响应拦截器中拒绝它将使得承诺的调用者进入错误处理。 所以当这样做时

$http.get('some_url')
.then(succes)
.catch(err)

拒绝承诺将调用catch函数。因此,您没有正确的通用错误处理,但您的承诺被拒绝了,这很有用: - )

答案 2 :(得分:1)

如果您想将http响应传递给responseError处理程序,您可以这样做:

$httpProvider.interceptors.push(function($q) {

    var self = {

        response: function (response) {

            if (response.data.error) {
                return self.responseError(response);
            }

            return response;
        },

        responseError: function(response) {
            // ... do things with the response
        }
    }
    return self;
});
相关问题