Coo*_*SyS 3 c# asp.net-mvc-4 angularjs
我试图向用户返回一个自定义错误消息,让他们知道出现错误时出了什么问题,但我已经尝试了所有内容来显示消息,似乎没有任何东西正在捕获它.这是我的角度代码:
$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;
});
}
Run Code Online (Sandbox Code Playgroud)
这是它调用的styleAPIservice函数:
styleAPI.addStyle = function (style) {
return $http.post(AppRoot + "api/StyleAPI/",
JSON.stringify(style),
{
headers: {
'Content-Type': 'application/json'
}
});
}
Run Code Online (Sandbox Code Playgroud)
这是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;
}
Run Code Online (Sandbox Code Playgroud)
以下是发生错误时返回的内容(例如Style已存在):
An error occurred while saving style: [object Object]|undefined|undefined|undefined
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?我觉得我到处搜索并尝试了所有可能的建议,但我只是不知道为什么我无法显示我的错误消息.
用.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
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12653 次 |
| 最近记录: |