您能否澄清一下 Web API 错误管理的最佳实践是什么。实际上,我不知道在我的 Api 请求中使用 try catch 是否是一个好的做法。
public Vb.Order PostOrderItem(Vb.Order order)
{
if (OAuth.isValid(Request.Headers.GetValues("Token").Single()) != true)
{
HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.Unauthorized);
throw new HttpResponseException(httpResponseMessage);
}
if (!ModelState.IsValid)
{
HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest);
throw new HttpResponseException(httpResponseMessage);
}
try
{
return Vb.Document.Generate(order);
}
catch (Exception ex)
{
logger.Error(ex);
HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest);
httpResponseMessage.Content = new StringContent(ex.Message);
throw new HttpResponseException(httpResponseMessage);
}
}
我感觉对服务器端代码使用 try catch 并不是一个好的做法,因为我只是记录我的 catch 并重新抛出异常。
Web API 中的错误处理被认为是横切关注点,应该放置在管道中的其他位置,这样开发人员就不需要关注横切关注点。
您应该阅读 ASP.NET Web API 中的异常处理
如果 Web API 控制器抛出未捕获的异常会发生什么?经过 默认情况下,大多数异常都会转换为 HTTP 响应 状态代码 500,内部服务器错误。
以及 ASP.NET Web API 2 中的全局错误处理。
您应该尽可能保持控制器倾斜。像原始代码一样的错误处理只会导致代码重复,并引起开发人员需要注意的不必要的担忧。开发人员应该关注核心问题,而不是交叉问题。通过只关注核心问题,上面的代码将如下所示:
[MyAuthentication]
[MyValidateModel]
public Vb.Order PostOrderItem(Vb.Order order)
{
return Vb.Document.Generate(order);
}
为什么这么瘦?
因为:
if (OAuth.isValid(Request.Headers.GetValues("Token").Single()) != true)
{
HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.Unauthorized);
throw new HttpResponseException(httpResponseMessage);
}
可以移至 ASP.NET Web API 2 中的身份验证过滤器,可以在控制器/操作上本地应用或全局应用以返回相关响应。
if (!ModelState.IsValid)
{
HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest);
throw new HttpResponseException(httpResponseMessage);
}
也可以移动到过滤器中,例如:
public class MyValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid)
{
actionContext.Response = actionContext.Request.CreateErrorResponse(
HttpStatusCode.BadRequest, actionContext.ModelState);
}
}
}
请参阅此链接ASP.NET Web API 中的异常处理 - 指南。有 4 级异常处理管道:
Web API 在异常处理方面为我们提供了很大的灵活性。回顾一下:
- 使用 HttpResponseException 或快捷方法在操作级别处理未处理的异常。
- 使用异常过滤器来处理多个操作和控制器上的特定未处理异常。
- 使用 ExceptionLogger 记录任何未处理的异常。
- 使用异常处理程序(每个应用程序一个)来处理应用程序范围内任何未处理的异常。
有多种方法,每一种都在逻辑对象图上更进一步;
本文列出了所有这些; http://www.codeproject.com/Articles/850062/Exception-handling-in-ASP-NET-MVC-methods-explaine
我发现使用更高级别的方法之一以避免重复代码很有用。