Sentinel授權規則-自定義異常結果


默認情況下,發生限流、降級、授權攔截時,都會拋出異常到調用方。如果要自定義異常時的返回結果,需要實現BlockExceptionHandler接口:

public class SentinelExceptionHandler implements BlockExceptionHandler { /** * 處理請求被限流、降級、授權攔截時拋出的異常:BlockException */
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception; }

 

而BlockException包含很多個子類,分別對應不同的場景:

異常                       說明
FlowException             限流異常
ParamFlowException        熱點參數限流的異常
DegradeException          降級異常
AuthorityException        授權規則異常
SystemBlockException      系統規則異常

 

自定義異常結果
我們在order-service中定義類,實現BlockExceptionHandler接口:

@Component public class SentinelExceptionHandler implements BlockExceptionHandler { @Override public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception { String msg = "未知異常"; int status = 429; if (e instanceof FlowException) { msg = "請求被限流了"; } else if (e instanceof ParamFlowException) { msg = "請求被熱點參數限流"; } else if (e instanceof DegradeException) { msg = "請求被降級了"; } else if (e instanceof AuthorityException) { msg = "沒有權限訪問"; status = 401; } response.setContentType("application/json;charset=utf-8"); response.setStatus(status); response.getWriter().println("{\"msg\": " + msg + ", \"status\": " + status + "}"); } }

 

總結
獲取請求來源的接口是什么?
RequestOriginParser

處理BlockException的接口是什么?
BlockExceptionHandler


免責聲明!

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



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