Web API 異常處理解決方案


  • 異常篩選器:在App_Start里面新建一個類WebApiExceptionFilterAttribute.cs(這實際上是定義了一個新的特性),它繼承於ExceptionFilterAttribute類,但是我們需要重寫里面的OnException()方法
  • 在接口級別上使用新定義的異常類,同時還需要在自定義異常類WebApiExceptionFilterAttribute.cs中定義錯誤信息,頁面顯示"不好意思,該方法不支持",而且它的Status Code: 501 This Func is Not Supported
1 [App_Start.WebApiExceptionFilter]
2 [HttpGet]
3 public string GetData(){
4     throw new NotImplementedException("不好意思,該方法不支持");
5 }
  • 在控制器級別使用異常過濾,直接在控制器上面標注特性即可;如果想要在多個控制器上同時啟用異常過濾,可以建立一個基類控制器,在該基類控制器上標注特性,其他控制器繼承該基類控制器即可
1 [App_Start.WebApiExceptionFilter]
2 public class TestException2Controller : ApiController{
3     [HttpGet]
4     public string GetData(){
5         throw new NotImplementedException("不好意思,該方法不支持");
6     }
7 }
8 [App_Start.WebApiExceptionFilter]
9 public class TestExceptionBaseController : ApiController{ }
 
  • 全部配置,對整個應用程序啟用異常過濾
 1 //在Global.asax全局配置里面添加
 2 public class WebApiApplication : System.Web.HttpApplication{
 3     protected void Application_Start(){
 4         GlobalConfiguration.Configuration.Filters.Add(new App_Start.WebApiExceptionFilterAttribute());
 5     }
 6 }
 7 //在WebApiConfig.cs文件的Register方法里面添加
 8 public static class WebApiConfig{
 9     public static void Register(HttpConfiguration config){
10         config.Filters.Add(new App_Start.WebApiExceptionFilterAttribute());
11 }}
  • 使用HttpResponseException類自定義異常信息
    • HttpResponseMessage 用於返回一個來自於客戶端的請求結果訊息,可以使用 HttpResponseMessage 自訂返回的內容,HttpResponseException 則是以當發生例外時用來返回客戶端錯誤訊息
    • 當呼叫 Web API 服務時發生了與預期上不同的錯誤時,理當應該中止程序返回錯誤訊息,這時對於錯誤的返回就該使用 HttpResponseException,而使用 HttpResponseMessage 則是代表着當客戶端發送了一個工作請求而 Web API 正確的完成了這個工作,就能夠使用 HttpResponseMessage 返回一個 201 的訊息,所以 HttpResponseMessage 與 HttpResponseException 在使用上根本的目標就是不同的,用 HttpResponseMessage 去返回一個例外錯誤也會讓程序結構難以辨別且不夠清晰
 1 [HttpGet]
 2 public string GetData_Ex(int id){
 3     if (id == 1){
 4         return "function is OK";
 5     }else{
 6         var response = new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound){
 7             Content = new StringContent("不好意思,沒有找到"+id.ToString()),
 8             ReasonPhrase = "object is not found"
 9         });
10         throw response;
11     }
12 }
  • 使用HttpError對象提供一致的方法響應正文中返回的錯誤信息,二者都可以向客戶端返回http狀態碼和錯誤訊息,並且都可以包含在HttpResponseException對象中發回到客戶端;但是,一般情況下,HttpError只有在向客戶端返回錯誤訊息的時候才會使用,而HttpResponseMessage對象既可以返回錯誤訊息,也可返回請求正確的消息
 1 [HttpGet]
 2 public HttpResponseMessage GetData_HttpError(){
 3     try{
 4         //業務邏輯
 5     }catch (Exception ex){
 6         return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message);
 7     }
 8     return Request.CreateResponse(HttpStatusCode.OK, "OKOKOK");
 9 }
10  
 1 public class WebApiExceptionFilterAttribute : ExceptionFilterAttribute{
 2     public override void OnException(HttpActionExecutedContext actionExecutedContext){
 3         //1.異常日志記錄(正式項目里面一般是用log4net記錄異常日志)
 4         Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "——" + actionExecutedContext.Exception.GetType().ToString() + ":" + actionExecutedContext.Exception.StackTrace);
 5         //2.返回調用方具體的異常信息
 6         if (actionExecutedContext.Exception is NotImplementedException){
 7             actionExecutedContext.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented){
 8                 Content = new StringContent("不好意思,該方法不支持"),//獲取或設置 HTTP 響應消息的內容
 9                 ReasonPhrase = "不好意思,該方法不支持"//獲取或設置通常由服務器發出的原因短語(與狀態代碼一起發出
10             };
11         }
12         else if(actionExecutedContext.Exception is TimeoutException){
13             actionExecutedContext.Response = new HttpResponseMessage(HttpStatusCode.RequestTimeout);
14         }
15         else{
16             //.....這里可以根據項目需要返回到客戶端特定的狀態碼。如果找不到相應的異常,統一返回服務端錯誤500
17             actionExecutedContext.Response = new HttpResponseMessage(HttpStatusCode.InternalServerError);
18         }
19         base.OnException(actionExecutedContext);
20     }
21 }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM