【发布时间】:2019-10-22 19:54:32
【问题描述】:
这很相似,但我的问题不同:Return content with IHttpActionResult for non-OK response
考虑到问题不同,我要求一个更简洁的答案,如果存在的话。
我的架构如下:
- Javascript/jQuery 调用后端控制器
- 后端控制器调用 WebAPI 服务
- WebAPI 服务查询 db(等)并返回数据
我有以下简化代码(Web API)...
示例 1 如果产品 ID 不存在则返回错误:
public IHttpActionResult GetProduct(int id)
{
var product = products.FirstOrDefault((p) => p.Id == id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
示例 2 如果产品 id 不存在则返回空数据:
public IHttpActionResult GetProduct(int id)
{
var product = products.FirstOrDefault((p) => p.Id == id);
return Ok(product);
}
客户端JS:
$.getJSON("example.json", function() {
alert("success");
})
.done(function() { alert('Product retrieved'); })
.fail(function() { alert('Product doesn't exist. '); })
.always(function() { ... });
我已经读过很多次了,使用异常来控制流是不好的做法,这实际上是如果我使用NotFound() 会发生什么,因为它会命中.fail 函数,这表明存在错误(没有)。
在另一种情况下,评论必须由插入评论的人以外的人批准:
public IHttpActionResult ApproveComment(int rowId, string userName)
{
try {
return Ok(BusinessLogicLayer.ApproveComment(rowId, userName));
}
catch(Exception ex)
{
// elmah.logerr...
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.InnerException == null ? ex.Message : ex.InnerException.Message));
}
}
BusinessLogicLayer:
public string ApproveComment(int rowId, string userName)
{
if (userName == _repository.GetInsertedCommentUserName()) {
return "You cannot approve your own comment.";
}
if(_repository.ApproveComment(rowId, userName)){
return "Comment approved";
}
}
或
public string ApproveComment(int rowId, string userName)
{
if (userName == _repository.GetInsertedCommentUserName()) {
throw new Exception("You cannot approve your own comment.");
}
if(_repository.ApproveComment(rowId, userName)){
return "Comment approved";
}
}
在不使用异常的情况下,向用户返回适当消息的简洁优雅的方式是什么?
或者我的想法是错误的,从用户的角度来看是“特殊”情况吗? IE.,“当我传入这个 ID 时,我希望得到一个产品返回,但可惜它不存在!”从开发人员/测试人员的角度来看,我认为这不会是一个例外情况,但从最终用户的角度来看——也许吧。
【问题讨论】:
-
如果您查看 en.wikipedia.org/wiki/List_of_HTTP_status_codes 有成功状态 204 - 无内容,这会解决您的问题吗?
标签: c# rest asp.net-web-api error-handling controller