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

HttpResponseException

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

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

 1 public Product GetProduct(int id)
 2 {
 3     Product item = repository.Get(id);
 4     if (item == null)
 5     {
 6         throw new HttpResponseException(HttpStatusCode.NotFound);
 7     }
 8     return item;
 9 }
10 
11 public Product GetProduct(int id)
12 {
13     Product item = repository.Get(id);
14     if (item == null)
15     {
16         var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
17         {
18             Content = new StringContent(string.Format("No product with ID = {0}", id)),
19             ReasonPhrase = "Product ID Not Found"
20         }
21         throw new HttpResponseException(resp);
22     }
23     return item;
24 }
View Code

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 方式1:
 2 public class ProductsController : ApiController
 3 {
 4     [NotImplExceptionFilter]
 5     public Contact GetContact(int id)
 6     {
 7         throw new NotImplementedException("This method is not implemented");
 8     }
 9 }
10 
11 方式2:
12 [NotImplExceptionFilter]
13 public class ProductsController : ApiController
14 {
15     // ...
16 }
17 
18 方式3:
19 GlobalConfiguration.Configuration.Filters.Add(
20     new ProductStore.NotImplExceptionFilterAttribute());
View Code

HttpError

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

 1 public HttpResponseMessage GetProduct(int id)
 2 {
 3     Product item = repository.Get(id);
 4     if (item == null)
 5     {
 6         var message = string.Format("Product with id = {0} not found", id);
 7         return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);
 8     }
 9     else
10     {
11         return Request.CreateResponse(HttpStatusCode.OK, item);
12     }
13 }
View Code

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

 1 public Product GetProduct(int id)
 2 {
 3     Product item = repository.Get(id);
 4     if (item == null)
 5     {
 6         var message = string.Format("Product with id = {0} not found", id);
 7         throw new HttpResponseException(
 8             Request.CreateErrorResponse(HttpStatusCode.NotFound, message));
 9     }
10     else
11     {
12         return item;
13     }
14 }
15 
16 public HttpResponseMessage PostProduct(Product item)
17 {
18     if (!ModelState.IsValid)
19     {
20         return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
21     }
22 
23     // Implementation not shown...
24 }
View Code
原文地址:https://www.cnblogs.com/goodlucklzq/p/4458762.html