WebApi異常處理解決方案

2022-02-17 23:53:28 字數 1626 閱讀 2005

一、使用異常篩選器捕獲所有異常

public class webapiexceptionfilterattribute : exceptionfilterattribute 

else if (actionexecutedcontext.exception is timeoutexception)

//.....這裡可以根據專案需要返回到客戶端特定的狀態碼。如果找不到相應的異常,統一返回服務端錯誤500

else

base.onexception(actionexecutedcontext);}}

**解析:通過判斷異常的具體型別,向客戶端返回不同的http狀態碼,示例裡面寫了兩個,可以根據專案的實際情況加一些特定的我們想要捕獲的異常,然後將對應的狀態碼寫入http請求的response裡面,對於一些我們無法判斷型別的異常,統一返回服務端錯誤500。關於http的狀態碼,framework裡面定義了一些常見的型別,我們大概看看:

#region 程式集 system.dll, v4.0.0.0

//c:\program files (x86)\reference assemblies\microsoft\framework\.netframework\v4.5\system.dll

#endregion

using

system;

namespace

system.net

}

定義好了異常處理方法,剩下的就是如何使用了。可以根據實際情況,在不同級別使用統一的異常處理機制。

執行到異常後,會先進到onexception方法:

執行完成之後瀏覽器檢視:

如果需要,甚至可以向status code裡面寫入自定義的描述資訊,並且還可以向我們的response的content裡面寫入我們想要的資訊。我們稍微改下onexception方法:

if (actionexecutedcontext.exception is notimplementedexception)

看看reasonphrase描述資訊

看看response的描述資訊

如果想要某乙個或者多個控制器裡面的所有介面都使用異常過濾,直接在控制器上面標註特性即可。

WebApi 異常處理解決方案

public class webapiexceptionfilterattribute exceptionfilterattribute else if actionexecutedcontext.exception is timeoutexception 這裡可以根據專案需要返回到客戶端特定的狀態...

WebApi 異常處理解決方案

1.繼承exceptionfilterattribute類,重寫onexception方法 public class webapiexceptionfilterattribute exceptionfilterattribute string errmsg jsonconvert.serialize...

Springboot異常錯誤處理解決方案詳解

1.在有模板引擎的情況下 springboot會預設找 templates error 錯誤狀態碼.html,所以我們要定製化錯誤頁面就可以到templates error下建立乙個 對應錯誤狀態碼.html html檔案,當發生此狀態碼的錯誤springboot就會來到對應的頁面。同時如果我們想讓...