简体   繁体   English

如何从$ httpProvider拦截器的“响应”功能引发错误

[英]How to throw error from 'reponse' function of $httpProvider interceptor

I am making a http interceptor in angular and I want to make throw error from response of $httpProvider interceptor. 我正在用角度制作一个http拦截器,并且我想从$httpProvider拦截器的response中引发抛出错误。

As per the documentation: 根据文档:

response : interceptors get called with http response object. response :使用http响应对象调用拦截器。 The function is free to modify the response object or create a new one. 该函数可以自由修改响应对象或创建新对象。 The function needs to return the response object directly, or as a promise containing the response or a new response object. 该函数需要直接返回响应对象,或者作为包含响应或新响应对象的承诺。

responseError : interceptor gets called when a previous interceptor threw an error or resolved with a rejection. responseError前一个拦截器抛出错误或被拒绝解决时, 拦截器将被调用。

I want to do the bold part in above quote so that a response with status 200 (I've a condition there) is routed to responseError where I will handle the error. 我想在上面的引号中做粗体部分,以便将状态为200(我有一个条件)的responseError路由到responseError ,我将在其中处理错误。 Not returning a response throws following error: 不返回响应会引发以下错误:

Cannot read property 'data' of undefined

I do not want to return the response but want to pass it to next handler ie responseError . 我不想返回响应,但想将其传递给下一个处理程序,即responseError

How can I do that? 我怎样才能做到这一点? I hope I made it clear. 我希望我说清楚了。 Thanks. 谢谢。

Update (Code Below): 更新(下面的代码):

app.config(['$httpProvider', function($httpProvider) {
    interceptor.$inject = ['$q', '$rootScope'];
    $httpProvider.interceptors.push(interceptor);

    function interceptor($q, $rootScope) {
        return {
            response: response,
            responseError: responseError
        };

        function response(response) {
            if (response.data.rs == "F") {
                // I want to route it responseError -->
            } else {
                return response;
            }
        }

        function responseError(response) {
            // I want to handle that error here
        }
    }

}]);

Use: 采用:

return $q.reject(response);

Also make sure you return: (Read about it here ) 还要确保您返回:( 在此处阅读有关内容)

return response || $q.when(response);

instead of: 代替:

return response;

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

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