Angular $ http错误响应statusText始终未定义

时间:2014-08-01 13:08:27

标签: c# angularjs asp.net-mvc-4

我正在尝试向用户返回一条自定义错误消息,让他们知道出现错误时出了什么问题,但我已经尝试了所有内容来显示消息,似乎没有任何东西正在捕获它。这是我的角度代码:

$scope.save = function (style) {
    styleAPIservice.addStyle(style).success(function () {
        $scope.success = "Style added successfully";
    }).error(function (data, status, headers, config, statusText) {
        $scope.error = "An error occurred while saving style: " + data + "|"+data.data+"|"+data.statusText+"|"+statusText;
    });
}

以下是它正在调用的 styleAPIservice 函数:

styleAPI.addStyle = function (style) {
    return $http.post(AppRoot + "api/StyleAPI/",
        JSON.stringify(style),
            {
                headers: {
                    'Content-Type': 'application/json'
                }
            });
}

这是 API 功能:

[HttpPost]
public HttpResponseMessage PostStyle(Style style)
{
    if (string.IsNullOrEmpty(style.Pattern.PatternName) || string.IsNullOrEmpty(style.StockNumber))
        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Pattern Name and Stock Number are required.");

    var checkStyle = StyleRepository.LoadStyleByStockNumber(style.StockNumber);
    if (checkStyle != null)
        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Style number already exists. Please use update.");

    try
    {
        // Save style
    }
    catch (Exception ex)
    {
        return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Error creating style: " + ex.Message);
    }

    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, style);
    response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = style.StyleId }));
    return response;
}

以下是发生错误时返回的内容(例如Style已经存在):

An error occurred while saving style: [object Object]|undefined|undefined|undefined

我做错了什么?我觉得我到处搜索并尝试了所有可能的建议,但我只是不知道为什么我无法显示我的错误信息。

3 个答案:

答案 0 :(得分:9)

用.catch()替换.error()。

$http.post('/url',json)
    .success(function(data, status, headers, config){

      // some code here

    })
    .catch(function(data, status, headers, config){ // <--- catch instead error

        data.statusText; //contains the error message

    });

答案 1 :(得分:2)

对于可能遇到此问题的其他人,该邮件位于data.Message。我通过调试JS找到了它。

答案 2 :(得分:2)

StatusText只能通过使用来自$ http的.then,而不是来自.Post帮助器方法而不是来自.success .error。

    function handleSuccess(data, status, headers, config, statusText){
       //some function of your own invention
    }
    function handleError(data, status, headers, config, statusText){
       //some function of your own invention
    }
    //borrowed from angularJs Http module
    function headersGetter(headers) {
        var headersObj = isObject(headers) ? headers : undefined;

        return function(name) {
            if (!headersObj) headersObj =  parseHeaders(headers);

            if (name) {
                var value = headersObj[lowercase(name)];
                if (value === void 0) {
                    value = null;
                }
                return value;
            }

            return headersObj;
        };
    }

    //borrowed from angularJs Http module
    function isSuccess(status) {
        var istatus = Math.max(status, 0);
        return 200 <= istatus && istatus < 300;
    }

    $scope.postMyData = function ($http)
    {
        var req = {
            method: 'POST',
            url: 'destinationURL.html',
            headers: {
                'Content-Type': 'application/json'
            },
            data: $scope,
        };

        // example response from :
        //http://plnkr.co/edit/atRTBQC62YdZzKH8mWqu?p=preview
        //{
        //  "data":"Hello, $http!",
        //  "status":200,
        //  "config":{
        //    "method":"GET",
        //    "transformRequest":[null],
        //    "transformResponse":[null],
        //    "url":"http-hello.html",
        //    "cache":{},
        //    "headers":{"Accept":"application/json, text/plain, */*"}
        //  },
        //    "statusText":"OK"}

        $http(req).
            then(function (response) {
                var data = response.data;
                var status = response.status;
                var headers = headersGetter(headers)
                var config = response.config;
                var statusText = response.statusText;

                scope.messageToUsers = (isSuccess(response.status))
                    ? handleSuccess(data, status, headers, config, statusText)
                    : handleError(data, status, headers, config, statusText);
            })
    }