AngularJS拦截器ResponseError响应未定义

时间:2015-09-23 12:45:47

标签: javascript angularjs

我有这个处理$ 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中我可以看到:

  
    

获取http://localhost:54326/orders?orderNumber=M0002663&readCoreHistory=true 500(内部服务器错误)

  

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

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

更新

我现在知道造成这个问题的原因了。 我有一个看起来像这样的拦截器:

.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);
    };
}])

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

2 个答案:

答案 0 :(得分:0)

你可以尝试这样做:

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

答案 1 :(得分:0)

如果我把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);
});

这也可以。

相关问题