WebApi2官网学习记录---异常处理
HttpResponseException
?當WebAPI的控制器拋出一個未捕獲的異常時,默認情況下,大多數異常被轉為status code為500的http response即服務端錯誤。
HttpResonseException是一個特別的情況,這個異??梢苑祷厝我庵付ǖ膆ttp 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
- 在action上
- 在Controller上
- 在全局
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
總結
以上是生活随笔為你收集整理的WebApi2官网学习记录---异常处理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 关于学习编程的一些看法
- 下一篇: 求火柴人向左跑和向右跑的gif