【问题标题】:AngularJS Interceptor ResponseError response undefinedAngularJS拦截器ResponseError响应未定义
【发布时间】:2015-09-24 22:03:57
【问题描述】:

我有这个处理程序来处理 $http 请求。

看起来像这样:

.service('ApiHandler', ['$q', '$http', '$injector', 'apiUrl', 'ErrorService', 'toastr', function ($q, $http, $injector, apiUrl, errorService, toastr) {

    // Private function to build our request
    var buildRequest = function (url, method, data, params) {

        // Create our deferred promise
        var deferred = $q.defer();

        // Create the model
        var model = {
            method: method,
            url: apiUrl + url,
            data: data,
            params: params
        };

        console.log(model);

        // Build our request
        $http(model).then(function (response) {

            console.log('we have a response');

            // Resolve our response
            deferred.resolve(response.data || response);

        // If we have an error
        }, function (error) {

            console.log('we have an error');

            // Process our error
            processedError = errorService.process(error);

            // Display our error
            toastr.error(processedError.message, processedError.title);
        });

        // Return our promise
        return deferred.promise;
    };

    // GET
    this.get = function (url, params) {
        return buildRequest(url, 'GET', null, params);
    };

    // POST
    this.post = function (url, data) {
        return buildRequest(url, 'POST', data);
    };

    // PUT
    this.put = function (url, data) {
        return buildRequest(url, 'PUT', data);
    };

    // DELETE
    this.delete = function (url, data) {
        return buildRequest(url, 'DELETE', data);
    };
}])

这个想法是,当有人执行任何 http 请求时,如果请求成功,它将显示数据(仅显示数据),如果由于某种原因出错,它将处理错误并显示一个很好的错误消息。

这是有效的,但我不确定它为什么停止了。 我故意在我的 API 中放了一个错误以强制出现 500 内部服务器错误,在 chrome 中我可以看到:

GET http://localhost:54326/orders?orderNumber=M0002663&readCoreHistory=true500(内部服务器错误)

问题是,收到此错误后,我希望在控制台中看到我们有错误,但我没有。我得到我们有回应

有谁知道为什么是成功处理程序而不是错误处理程序?

更新

我现在知道是什么导致了这个问题。 我有一个看起来像这样的拦截器:

.factory('AuthInterceptorService', ['$location', function ($location) {

    // The request function
    var request = function (config) {

        // Get our stored auth data
        var authData = angular.fromJson(sessionStorage.authorizationData);

        // Set our headers to the request headers or a new object
        config.headers = config.headers || {};

        // If we have any auth data
        if (authData) {

            // Set our authorization header
            config.headers.Authorization = 'Bearer ' + authData.token;
        }

        // Return our config
        return config;
    };

    // The response function
    var responseError = function (response) {

        console.log('error handler');

        // If our response status is unauthorized
        if (response.status === 401) {

            // Redirect to the login screen
            $location.path('/security/login');
        }
    };

    return {
        request: request,
        responseError: responseError
    };
}])

因为你的 responseError 函数没有返回/拒绝任何东西,所以我把它改成了这样:

.factory('AuthInterceptorService', ['$q', '$location', 'ErrorService', function ($q, $location, errorService) {

    // The request function
    var request = function (config) {

        // Get our stored auth data
        var authData = angular.fromJson(sessionStorage.authorizationData);

        // Set our headers to the request headers or a new object
        config.headers = config.headers || {};

        // If we have any auth data
        if (authData) {

            // Set our authorization header
            config.headers.Authorization = 'Bearer ' + authData.token;
        }

        // Return our config
        return config;
    };

    // The response function
    var responseError = function (response) {

        console.log('error handler');

        // If our response status is unauthorized
        if (response.status === 401) {

            // Redirect to the login screen
            $location.path('/security/login');
        } else {

            // Process our error
            var error = errorService.process(response);

            console.log(error);

            // Reject our response
            return $q.reject(error);
        }
    };

    return {
        request: request,
        responseError: responseError
    };
}])

我将我的 API 处理程序更改为:

.service('ApiHandler', ['$q', '$http', 'apiUrl', 'toastr', function ($q, $http, apiUrl, toastr) {

    // Private function to build our request
    var buildRequest = function (url, method, data, params) {

        // Create our deferred promise
        var deferred = $q.defer();

        // Create the model
        var model = {
            method: method,
            url: apiUrl + url,
            data: data,
            params: params
        };

        //console.log(model);

        // Build our request
        $http(model).success(function (response) {

            //console.log('we have a response');

            // Resolve our response
            deferred.resolve(response);

        // If we have an error
        }).error(function (error) {

            console.log('we have an error');

            console.log(error);

            // Display our error
            toastr.error(error.message, error.title);

            deferred.reject();
        });

        // Return our promise
        return deferred.promise;
    };

    // GET
    this.get = function (url, params) {
        return buildRequest(url, 'GET', null, params);
    };

    // POST
    this.post = function (url, data) {
        return buildRequest(url, 'POST', data);
    };

    // PUT
    this.put = function (url, data) {
        return buildRequest(url, 'PUT', data);
    };

    // DELETE
    this.delete = function (url, data) {
        return buildRequest(url, 'DELETE', data);
    };
}])

现在实际上正在调用错误处理程序,但错误参数未定义。有谁知道为什么?

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    你可以尝试这样做吗:

    $http.get('/someURL').success(function(data, status, header, config) {
        // success handler
    }).error(function(data, status, header, config) {
        // error handler
    });
    

    【讨论】:

    • 如果我这样做,当出现错误时不会调用成功处理程序,但也不会调用错误处理程序。我不知道为什么:/
    【解决方案2】:

    如果我把我的 ApiHandler 改回这个:

    .service('ApiHandler', ['$q', '$http', 'apiUrl', 'toastr', function ($q, $http, apiUrl, toastr) {
    
        // Private function to build our request
        var buildRequest = function (url, method, data, params) {
    
            // Create our deferred promise
            var deferred = $q.defer();
    
            // Create the model
            var model = {
                method: method,
                url: apiUrl + url,
                data: data,
                params: params
            };
    
            // Build our request
            $http(model).then(function (response) {
    
                // Resolve our response
                deferred.resolve(response.data);
    
            // If we have an error
            }, function (response) {
    
                // Display our error
                toastr.error(response.message, response.title);
    
                deferred.reject();
            });
    
            // Return our promise
            return deferred.promise;
        };
    
        // GET
        this.get = function (url, params) {
            return buildRequest(url, 'GET', null, params);
        };
    
        // POST
        this.post = function (url, data) {
            return buildRequest(url, 'POST', data);
        };
    
        // PUT
        this.put = function (url, data) {
            return buildRequest(url, 'PUT', data);
        };
    
        // DELETE
        this.delete = function (url, data) {
            return buildRequest(url, 'DELETE', data);
        };
    }])
    

    效果很好。

    我也可以做一个

    .success(function (response) {
    
        return response;
    }).catch(function (response) {
    
        toastr.error(response.message, response.title);
    });
    

    这样也行。

    【讨论】:

      猜你喜欢
      • 2019-02-11
      • 1970-01-01
      • 2018-09-27
      • 2018-01-05
      • 2015-05-15
      • 2022-07-02
      • 1970-01-01
      • 2012-08-11
      相关资源
      最近更新 更多