Angular $http 错误响应 statusText 始终未定义 [英] Angular $http error response statusText always undefined
问题描述
我正在尝试向用户返回自定义错误消息,让他们知道发生错误时出了什么问题,但我已经尝试了所有方法来显示该消息,但似乎没有任何内容可以捕获它.这是我的角度代码:
I am trying to return a custom error message to the user to let them know what went wrong if an error occurs, but I have tried everything to display the message and nothing seems to be capturing it. Here is my angular code:
$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 函数:
Here is the styleAPIservice function it's calling:
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 已存在):
And here is what is returned when an error occurs (such as Style already exists):
An error occurred while saving style: [object Object]|undefined|undefined|undefined
我做错了什么?我觉得我已经到处搜索并尝试了所有可能的建议,但我不知道为什么我无法显示我的错误消息.
What am I doing wrong? I feel like I've searched everywhere and tried every possible suggestion, but I am just at a loss as to why I can't display my error messages.
推荐答案
对于可能遇到此问题的任何其他人,消息位于 data.Message
中.我是通过调试JS找到的.
For anyone else who may have had this issue, the message was in data.Message
. I found it by debugging the JS.
这篇关于Angular $http 错误响应 statusText 始终未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!