自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

如何友好的處理 WebApi 中拋出的錯(cuò)誤

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

[[384418]]

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

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

WebAPI 中的 HttpResponseException

你可以在 Action 中使用 HttpResponseException 來(lái)包裝指定的 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); 

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

WebAPI 中使用 HttpError

除了直接實(shí)例化 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 中使用 異常過(guò)濾器

異常過(guò)濾器是一種可以在 WebAPI 中捕獲那些未得到處理的異常的過(guò)濾器,要想創(chuàng)建異常過(guò)濾器,你需要實(shí)現(xiàn) IExceptionFilter 接口,不過(guò)這種方式比較麻煩,更快捷的方法是直接繼承 ExceptionFilterAttribute 并重寫里面的 OnException() 方法即可,這是因?yàn)?ExceptionFilterAttribute 類本身就實(shí)現(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.    } 

下面的代碼片段展示了如何通過(guò)重寫 ExceptionFilterAttribute.OnException() 方法來(lái)創(chuàng)建一個(gè)自定義異常過(guò)濾器,請(qǐng)注意下面的代碼是如何捕獲在 Action 中拋出的異常,并將捕獲到的異常轉(zhuǎn)換為 HttpStatusResponse 實(shí)體,然后塞入合適的 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.  } 

接下來(lái)將自定義的異常過(guò)濾器添加到 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 級(jí)別上,下面的代碼分別展示了如何將其控制在 Action 和 Controller 上。

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

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

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

 

責(zé)任編輯:武曉燕 來(lái)源: 碼農(nóng)讀書
相關(guān)推薦

2009-03-18 08:59:28

throw異常Java

2021-01-14 21:37:01

JavaScript開發(fā)代碼

2014-06-27 09:34:03

AngularJS

2023-11-30 07:15:36

GolangRecover

2023-12-26 22:05:53

并發(fā)代碼goroutines

2021-09-01 07:21:46

堆棧Gopanic

2025-02-10 09:49:00

2024-04-16 12:18:05

編程異常處理錯(cuò)誤返回

2016-09-07 20:28:17

MySQL存儲(chǔ)數(shù)據(jù)庫(kù)

2018-03-05 19:20:49

LinuxWordPressHTTP

2021-01-28 13:16:27

Python編程語(yǔ)言

2023-10-26 12:05:14

Golang開發(fā)

2018-08-30 10:28:05

修復(fù)Windows 10IntcOED

2017-05-26 11:32:44

程序應(yīng)用測(cè)試

2023-04-17 07:41:02

Rust網(wǎng)絡(luò)數(shù)據(jù)

2024-09-23 08:10:00

.NET開發(fā)

2021-03-02 09:12:25

Java異常機(jī)制

2022-05-06 08:00:51

Golang編程語(yǔ)言Java

2021-04-14 07:08:14

Nodejs錯(cuò)誤處理

2024-03-05 18:15:28

AsyncAwait前端
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)