日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
如何友好的處理WebApi中拋出的錯誤

本文轉(zhuǎn)載自微信公眾號「碼農(nóng)讀書」,作者碼農(nóng)讀書。轉(zhuǎn)載本文請聯(lián)系碼農(nóng)讀書公眾號。

在西盟等地區(qū),都構(gòu)建了全面的區(qū)域性戰(zhàn)略布局,加強發(fā)展的系統(tǒng)性、市場前瞻性、產(chǎn)品創(chuàng)新能力,以專注、極致的服務(wù)理念,為客戶提供做網(wǎng)站、成都網(wǎng)站制作 網(wǎng)站設(shè)計制作按需開發(fā)網(wǎng)站,公司網(wǎng)站建設(shè),企業(yè)網(wǎng)站建設(shè),品牌網(wǎng)站設(shè)計,成都全網(wǎng)營銷,外貿(mào)網(wǎng)站建設(shè),西盟網(wǎng)站建設(shè)費用合理。

微軟的 ASP.NET Web API 是一個輕量級的web框架,可用來構(gòu)建基于 http 無狀態(tài)的rest服務(wù),異常是一種運行時錯誤,異常處理是一種處理運行時錯誤的技術(shù),每一個開發(fā)者都應(yīng)該知道如何處理 Web API 中的異常,并且在 Action 中使用合適的 錯誤碼 和 錯誤信息 進行包裝。

WebAPI 中的 HttpResponseException

你可以在 Action 中使用 HttpResponseException 來包裝指定的 HttpCode 和 HttpMessage,如下例子所示:

 
 
 
  1. public Employee GetEmployee(int id) 
  2.     Employee emp = employeeRepository.Get(id); 
  3.     if (emp == null) 
  4.     { 
  5.         var response = new HttpResponseMessage(HttpStatusCode.NotFound) 
  6.         { 
  7.             Content = new StringContent("Employee doesn't exist", System.Text.Encoding.UTF8, "text/plain"), 
  8.             StatusCode = HttpStatusCode.NotFound 
  9.         } 
  10.         throw new HttpResponseException(response); 
  11.     } 
  12.     return emp; 

如果你的 Action 返回的是 IHttpActionResult,那么可將 GetEmployee() 方法修改如下:

 
 
 
  1. public IHttpActionResult GetEmployee(int id) 
  2.     Employee emp = employeeRepository.Get(id); 
  3.     if (emp == null) 
  4.     { 
  5.         var response = new HttpResponseMessage(HttpStatusCode.NotFound) 
  6.         { 
  7.             Content = new StringContent("Employee doesn't exist", System.Text.Encoding.UTF8, "text/plain"), 
  8.             StatusCode = HttpStatusCode.NotFound 
  9.         } 
  10.         throw new HttpResponseException(response); 
  11.     } 
  12.     return Ok(emp); 

從上面的代碼可以看出,錯誤碼 和 錯誤消息 都賦給了 Response 對象,然后包裝到了 HttpResponseException 進行返回。

WebAPI 中使用 HttpError

除了直接實例化 HttpResponseMessage 類,還可以使用 Request.CreateErrorResponse() 快捷的創(chuàng)建 HttpResponseMessage 類,如下代碼所示:

 
 
 
  1. public IActionResult GetEmployee(int id) 
  2.     Employee emp = employeeRepository.Get(id); 
  3.     if (emp == null) 
  4.     { 
  5.        string message = "Employee doesn't exist"; 
  6.         throw new HttpResponseException( 
  7.             Request.CreateErrorResponse(HttpStatusCode.NotFound, message)); 
  8.     } 
  9.     return Ok(emp); 

WebAPI 中使用 異常過濾器

異常過濾器是一種可以在 WebAPI 中捕獲那些未得到處理的異常的過濾器,要想創(chuàng)建異常過濾器,你需要實現(xiàn) IExceptionFilter 接口,不過這種方式比較麻煩,更快捷的方法是直接繼承 ExceptionFilterAttribute 并重寫里面的 OnException() 方法即可,這是因為 ExceptionFilterAttribute 類本身就實現(xiàn)了 IExceptionFilter 接口,如下代碼所示:

 
 
 
  1. [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] 
  2.    public abstract class ExceptionFilterAttribute : FilterAttribute, IExceptionFilter, IFilter 
  3.    { 
  4.  
  5.        protected ExceptionFilterAttribute(); 
  6.  
  7.        public virtual void OnException(HttpActionExecutedContext actionExecutedContext); 
  8.        public virtual Task OnExceptionAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken); 
  9.    } 

下面的代碼片段展示了如何通過重寫 ExceptionFilterAttribute.OnException() 方法來創(chuàng)建一個自定義異常過濾器,請注意下面的代碼是如何捕獲在 Action 中拋出的異常,并將捕獲到的異常轉(zhuǎn)換為 HttpStatusResponse 實體,然后塞入合適的 httpcode 和 httpmessage,如下代碼所示:

 
 
 
  1. public class CustomExceptionFilter : ExceptionFilterAttribute 
  2.  { 
  3.      public override void OnException(HttpActionExecutedContext actionExecutedContext) 
  4.      { 
  5.          HttpStatusCode status = HttpStatusCode.InternalServerError; 
  6.          String message = String.Empty; 
  7.          var exceptionType = actionExecutedContext.Exception.GetType(); 
  8.          if (exceptionType == typeof(UnauthorizedAccessException)) 
  9.          { 
  10.              message = "Access to the Web API is not authorized."; 
  11.              status = HttpStatusCode.Unauthorized; 
  12.          } 
  13.          else if (exceptionType == typeof(DivideByZeroException)) 
  14.          { 
  15.              message = "Internal Server Error."; 
  16.              status = HttpStatusCode.InternalServerError; 
  17.          } 
  18.          else 
  19.          { 
  20.              message = "Not found."; 
  21.              status = HttpStatusCode.NotFound; 
  22.          } 
  23.          actionExecutedContext.Response = new HttpResponseMessage() 
  24.          { 
  25.              Content = new StringContent(message, System.Text.Encoding.UTF8, "text/plain"), 
  26.              StatusCode = status 
  27.          }; 
  28.          base.OnException(actionExecutedContext); 
  29.      } 
  30.  } 

接下來將自定義的異常過濾器添加到 HttpConfiguration 全局集合中,如下代碼所示:

 
 
 
  1. public static void Register(HttpConfiguration config) 
  2.         { 
  3.             config.MapHttpAttributeRoutes(); 
  4.             config.Routes.MapHttpRoute( 
  5.                 name: "DefaultApi", 
  6.                 routeTemplate: "api/{controller}/{id}", 
  7.                 defaults: new { id = RouteParameter.Optional } 
  8.             ); 
  9.             config.Formatters.Remove(config.Formatters.XmlFormatter); 
  10.             config.Filters.Add(new CustomExceptionFilter()); 
  11.         } 

除了將自定義異常設(shè)置到全局上,你還可以縮小粒度到 Controller 或者 Action 級別上,下面的代碼分別展示了如何將其控制在 Action 和 Controller 上。

 
 
 
  1. [DatabaseExceptionFilter] 
  2. public class EmployeesController : ApiController 
  3.     //Some code 
  4.  
  5.  [CustomExceptionFilter] 
  6.  public IEnumerable Get() 
  7.  { 
  8.     throw new DivideByZeroException();  
  9.  } 

ASP.NET Web API 提供了強大的 HttpResponseException 來包裝異常信息,默認情況下,當 WebAPI 中拋出異常,系統(tǒng)默認使用 Http StateCode = 500 作為回應(yīng),也即:Internal Server Error. ,場景就來了,如果你會用 HttpResponseException 的話,就可以改變這種系統(tǒng)默認行為,自定義錯誤碼和錯誤信息讓結(jié)果更加清晰語義化。

譯文鏈接:https://www.infoworld.com/article/2994111/how-to-handle-errors-in-aspnet-web-api.html


新聞標題:如何友好的處理WebApi中拋出的錯誤
網(wǎng)站URL:http://www.dlmjj.cn/article/dpjdgpg.html