简体   繁体   English

使用angularJS http服务捕获类似代理错误的错误

[英]Catch error like proxy error with angularJS http service

Is it possible to catch errors like 502 Proxy Error in the $http service from Angular1? 是否可以在Angular1的$ http服务中捕获诸如502 Proxy Error之类的错误? Normally the server is returning some HTTP status code like 500 and in the body an error message. 通常,服务器会返回一些HTTP状态代码(例如500),并在正文中返回错误消息。

Errors like this are exactly the same of course, it's an 502 error and the body is some HTML code (default apache), so I get that HTML code as error message and my application wil show that code as error. 像这样的错误当然是完全相同的,它是502错误,主体是一些HTML代码(默认的Apache),所以我将HTML代码作为错误消息得到,并且我的应用程序会将该代码显示为错误。

Is there a way to catch those errors and rewrite them to user friendly error messages? 有没有办法捕获这些错误并将其重写为用户友好的错误消息?

For this you can use your own httpInterceptor kinda like this: 为此,您可以使用自己的httpInterceptor有点像这样:

app.config(['$httpProvider', function($httpProvider){
    $httpProvider.interceptors.push('myhttpInterceptor');
}]);
app.factory('myhttpInterceptor', ['$q', '$injector', function($q, $injector){
    return {
        // optional method
        'request': function(config) {
            // do something on success
            return config;
        },

        // optional method
        'requestError': function(rejection) {
            // do something on error
            if (canRecover(rejection)) {
                return responseOrNewPromise
            }
            return $q.reject(rejection);
        },

        // optional method
        'response': function(response) {
            // do something on success
            return response;
        },

        // optional method
        'responseError': function(rejection) {

            // do something on error
            if (canRecover(rejection)) {
                return responseOrNewPromise
            }
            return $q.reject(rejection);
        }
    };
}]);

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

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