如何创建一个 http 拦截器以在“响应”中返回错误

How to create a http interceptor to return an error within 'response'?

本文关键字:响应 返回 错误 创建 何创建 http 一个      更新时间:2023-09-26

我有一个基本的角度http拦截器来处理我的所有错误。我需要检查返回的data是否都是每种类型的string,以将其处理为错误,而不是成功。

'response': function(response) {
    if(typeof response.data === 'string') {
        response.status = 422;
        return $q.reject(response);
    } else {
        return response;
    }
},
'responseError': function(rejection) {
    return $q.reject(rejection);
}

目前,如果datastring类型,它将输入正确的if语句,更改状态并返回。虽然,Angular并不认为这是一个错误。在我的http函数中,它既不调用成功也不调用错误回调。如果 API 返回合法错误,它将成功进入"响应错误",并按预期调用错误回调。

$http({
  method: 'POST',
  url: "http://mydomain/api/login",
  data: $.param({
     username: "test",
     password: "test"
  }),
  headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(successCallback(response), errorCallback(response));

如何让我的拦截器返回 Angular 可以识别的错误,以从我的 http 函数输入错误回调?

作为解决方案,您需要为常见的 ajaz 响应和响应错误创建一个工厂,如下所示,并将其注入到系统配置中,如下所示。

角度工厂在单独的文件中,并在索引中加载。

angular.module('yourApp').factory('myHttpInterceptor', function($q, $location) {
    return {
        // optional method
        'response': function(response) {
            // do something on success
            if(typeof response.data === 'string') {
                response.status = 422;
                return $q.reject(response);
            } else {
                return response;
            }
        },
        // optional method
       'responseError': function(rejection) {
          // do something on error
          return $q.reject(rejection);
        }
    };
});

现在在您的应用程序中拦截配置.js

.config([ '$httpProvider', 
    function($httpProvider) {
       $httpProvider.interceptors.push('myHttpInterceptor');
} ])

这对我有用。