AngularJS - 即使从Web API返回错误响应,$ http错误回调也无法正常工作

use*_*255 12 asp.net-web-api angularjs

我从服务器调用一个方法,它返回一个错误响应,如(400和500错误)但我的AngularJS错误回调没有被调用,即使我的状态代码包含400或500,也总是调用成功回调.谁能告诉我我做错了什么?请参阅下面的角度和WebAPI代码:

AngularJS代码:

$http.get("/api/employee")
    .success(function (data, status, headers, config) {
        console.log(data);
        return data;
    }).error(function (data, status, headers, config) {
        alert("error");
        return status;
});
Run Code Online (Sandbox Code Playgroud)

Web API代码:

public HttpResponseMessage Get(EmployeeModel employee)
{
     if (!ModelState.IsValid)
     {
         return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
     }
     //some other code
}
Run Code Online (Sandbox Code Playgroud)

Mah*_* K. 16

问题是有一个拦截器,它不能正确传播错误.

当调用拦截器的responseError时,它必须将异常传播到调用堆栈上,因此以下函数调用/回调将知道存在错误,而不是成功的响应.

$httpProvider.interceptors.push(function ($q, $rootScope) {

        return {
            request: function (config) {
                //the same config / modified config / a new config needs to be returned.
                return config;
            },
            requestError: function (rejection) {
                return $q.reject(rejection);
            },
            response: function (response) {
                //the same response/modified/or a new one need to be returned.
                return response;
            },
            responseError: function (rejection) {
                return $q.reject(rejection);
            }
        };
    });
Run Code Online (Sandbox Code Playgroud)

马蒂亚斯提到的观点是正确的,但它缺少返回元素.因此,如果您只是在responseError中拒绝,它不起作用,您需要返回拒绝,以便通知以下元素.


Mat*_*ley 6

我遇到了同样的问题,我自己仍然在想这个问题,但我发现了一个可能的问题.

.error()回调可以从执行,由一个可以防止HTTP响应截击(通过向注册$httpProvider.interceptors数组).

我正在使用一个模块来添加拦截器,所以我删除了它并手动编写了这些东西.


MBi*_*ski 1

我从来没有运气使用 .success 和 .error 选项,最终使用 .then 来处理所有事情,但还没有出现问题。我还应该指出,您不能像您试图做的那样从承诺中返回值。在输入 Promise 之前,您必须使用 var 声明一个变量,或者在 Promise 中分配一个新的 $scope 变量。

因此,经过这些更改,您的代码将如下所示:

var employees = $http({method:'GET', url:'/api/employee');
employees.then(function(data){
    $scope.employeeData = data;
}, function(data){
    //do error handling here
});
Run Code Online (Sandbox Code Playgroud)

此外,拥有一个集中的方法来处理错误有时会很有帮助,这可以使用 httpInterceptor 来完成(详细信息如下:在 angularjs 中处理来自代理的 HTTP 302 响应)。如果没有其他错误处理要做,这样做可以让您完全删除 .then 中的第二个函数,从而节省代码和带宽。