【问题标题】:Angular $http error response statusText always undefinedAngular $http 错误响应 statusText 始终未定义
【发布时间】:2015-03-04 08:47:26
【问题描述】:

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

$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

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

【问题讨论】:

  • 尝试调试代码以查看“数据”对象中的内容?
  • 好吧,我采纳了您的建议并在 Visual Studio 中进行了调试。消息在 data.Message 中。我现在觉得很笨。在这上面浪费了这么多时间! >.

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


【解决方案1】:

将 .error() 替换为 .catch()。

$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

    });

【讨论】:

  • 很高兴知道。谢谢!
【解决方案2】:

对于可能遇到此问题的其他任何人,该消息位于data.Message。我是通过调试JS找到的。

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2013-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-27
      • 2015-02-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多