WebApi2官网学习记录---异常处理

时间:2023-03-08 22:07:04

HttpResponseException

当WebAPI的控制器抛出一个未捕获的异常时,默认情况下,大多数异常被转为status code为500的http response即服务端错误。

HttpResonseException是一个特别的情况,这个异常可以返回任意指定的http status code,也可以返回具体的错误信息。

 public Product GetProduct(int id)
{
Product item = repository.Get(id);
if (item == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return item;
} public Product GetProduct(int id)
{
Product item = repository.Get(id);
if (item == null)
{
var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
{
Content = new StringContent(string.Format("No product with ID = {0}", id)),
ReasonPhrase = "Product ID Not Found"
}
throw new HttpResponseException(resp);
}
return item;
}

Exception Filters

可以自定义一个exception filter处理异常信息,当一个Controller中的方法抛出未捕获的异常(不包括HttpResponseException)filter会被执行。

Exception filters实现System.Web.Http.Filters.IExceptionFilter接口,最简单的方式是实现 System.Web.Http.Filters.ExceptionFilterAttribute类来进行自定义的exception filter

注册自定义的Exception Filters

  1. 在action上
  2. 在Controller上
  3. 在全局
 方式1:
public class ProductsController : ApiController
{
[NotImplExceptionFilter]
public Contact GetContact(int id)
{
throw new NotImplementedException("This method is not implemented");
}
} 方式2:
[NotImplExceptionFilter]
public class ProductsController : ApiController
{
// ...
} 方式3:
GlobalConfiguration.Configuration.Filters.Add(
new ProductStore.NotImplExceptionFilterAttribute());

HttpError

HttpError对象提供了一个统一的返回错误信息的方式

 public HttpResponseMessage GetProduct(int id)
{
Product item = repository.Get(id);
if (item == null)
{
var message = string.Format("Product with id = {0} not found", id);
return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);
}
else
{
return Request.CreateResponse(HttpStatusCode.OK, item);
}
}

在内部CreateErrorResponse创建了一个HttpError的实例,然后创建一个包含HttpError的HttpResponseMessage。返回的错误消息的格式与content-negotiation选择的formatter有关。

 public Product GetProduct(int id)
{
Product item = repository.Get(id);
if (item == null)
{
var message = string.Format("Product with id = {0} not found", id);
throw new HttpResponseException(
Request.CreateErrorResponse(HttpStatusCode.NotFound, message));
}
else
{
return item;
}
} public HttpResponseMessage PostProduct(Product item)
{
if (!ModelState.IsValid)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
} // Implementation not shown...
}