WebApi2官网学习记录---异常处理
HttpResponseException
?當(dāng)WebAPI的控制器拋出一個(gè)未捕獲的異常時(shí),默認(rèn)情況下,大多數(shù)異常被轉(zhuǎn)為status code為500的http response即服務(wù)端錯(cuò)誤。
HttpResonseException是一個(gè)特別的情況,這個(gè)異常可以返回任意指定的http status code,也可以返回具體的錯(cuò)誤信息。
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
?可以自定義一個(gè)exception filter處理異常信息,當(dāng)一個(gè)Controller中的方法拋出未捕獲的異常(不包括HttpResponseException)filter會(huì)被執(zhí)行。
Exception filters實(shí)現(xiàn)System.Web.Http.Filters.IExceptionFilter接口,最簡(jiǎn)單的方式是實(shí)現(xiàn)?System.Web.Http.Filters.ExceptionFilterAttribute類來(lái)進(jìn)行自定義的exception filter
? ?注冊(cè)自定義的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對(duì)象提供了一個(gè)統(tǒng)一的返回錯(cuò)誤信息的方式
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
?在內(nèi)部CreateErrorResponse創(chuàng)建了一個(gè)HttpError的實(shí)例,然后創(chuàng)建一個(gè)包含HttpError的HttpResponseMessage。返回的錯(cuò)誤消息的格式與content-negotiation選擇的formatter有關(guān)。
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
?
轉(zhuǎn)載于:https://www.cnblogs.com/goodlucklzq/p/4458762.html
總結(jié)
以上是生活随笔為你收集整理的WebApi2官网学习记录---异常处理的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 关于学习编程的一些看法
- 下一篇: GTONE清理维护建议方案