使用ASP.NET Web API进行error handling的最佳实践

您能否澄清一下Web API错误管理的最佳实践? 实际上,我不知道将try catch用于我的Api请求是否是一个好习惯。

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并重新抛出一个exception。

Web API中的error handling被认为是一个跨领域的问题,应该放在管道中的其他位置,这样开发人员就不需要关注跨领域的问题。

您应该阅读ASP.NET Web API中的exception处理

如果Web API控制器抛出未捕获的exception会发生什么? 默认情况下,大多数exception都会转换为状态代码为500的内部服务器错误的HTTP响应。

以及ASP.NET Web API 2中的全局error handling

你应该尽可能地让你的控制器保持精益。 像原始代码一样的error handling只会导致代码重复,并且开发人员需要注意不必要的问题。 开发人员应该关注核心问题,而不是跨领域问题。 只关注核心问题,上面的代码将如下所示:

 [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中的身份validation筛选器 ,可以在控制器/操作上本地应用,也可以全局应用于返回相关响应。

像这样的ASP.NET Web API中的模型validation

 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中的exception处理 – 指导教程 。 有4级exception处理管道:

  • 级别1 – HttpResponseException
  • 2级 – 例外filter
  • 3级 – 记录
  • 第4级 – exception处理程序

Web API在exception处理方面为我们提供了极大的灵活性。 回顾一下:

  • 使用HttpResponseException或快捷方法处理操作级别的未处理exception。
  • 使用exceptionfilter来处理多个操作和控制器上的特定未处理exception。
  • 使用ExceptionLogger记录任何未处理的exception。
  • 使用exception处理程序(每个应用程序一个)来处理应用程序范围内的任何未处理的exception。

有许多方法,每一步都进一步向上逻辑对象图;

本文列出了所有内容; http://www.codeproject.com/Articles/850062/Exception-handling-in-ASP-NET-MVC-methods-explaine

我发现使用其中一种更高级别的方法是有用的,以避免重复的代码。