淺談SpringBoot如何正確攔截thymeleaf異常
這是一篇可以正確攔截org.thymeleaf.exceptions.TemplateInputException異常的方法水礦石文章,不是解決業(yè)務問題的文章,比如不經(jīng)常見到的
org.thymeleaf.exceptions.TemplateProcessingE
xception: Could not parse as each: "message : xxx " (template: "xxxx" - line xx, col xx)
thymeleaf異常復現(xiàn)
你是故意的,還是不小心的 ----我是故意的
成功攔截,使用自定義試圖,捕獲主要信息,減去一大推報錯代碼,只顯示正常信息,顯得優(yōu)雅
為什么不生效
首先應該知道 @ControllerAdvice 是攔截不成功的,百世(試)不得其姐(解),正常來說,異常是會走下面這一行代碼的
@ControllerAdvice public class SysGlobalExceptionHandler<T> extends BasicController<Class<?>>{ @ExceptionHandler(Exception.class) public ResponseEntity<Object> exception(Throwable e) { // 處理異常 return ResponseEntity.status(this.response.getStatus()).body("Exception未定義異常" + e.getMessage()); } }
但是他是不正常的(因為攔截不到),為什么,我也不知道,但是AI是這么說的:@ControllerAdvice只能處理通過控制器拋出的異常,并不能處理其他組件拋出的異常。如果需要處理其他組件的異常,需要使用其他的異常處理機制。
聽君一席話,如菜鳥開大
怎么實現(xiàn)攔截生效呢
當然是重新實現(xiàn) ErrorController接口了
public Object errorHandle(){ ? ? //判斷狀態(tài)碼是500 ? ? if (this.response.getStatus() == HttpStatus.INTERNAL_SERVER_ERROR.value()) { ? ? // 獲取異常信息 ? ? Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception"); ? ? // 判斷是不是模板異常 ? ? if (throwable.getCause() instanceof TemplateInputException) { ? ? ? ? //這里其實也可以是TemplateInputException,throwable.getCause() instanceof TemplateInputException也可以是TemplateProcessingException,最終都是拋出TemplateProcessingException異常 ? ? ? ? TemplateProcessingException templateProcessingException = (TemplateProcessingException) throwable.getCause(); ? ? ? ? ParseException parseException = (ParseException) templateProcessingException.getCause(); ? ? ? ? //這里就是自定義邏輯了 ? ? ? ? this.msgFormat("模板出現(xiàn)異常 %s ", parseException.getLocalizedMessage()); ? ? ? ? modelAndView.setViewName("err"); ? ? ? ? // return this.Output(throwable.getClass()); ? ? ? ? //return ResponseEntity.status(this.response.getStatus()).body(parseException.getLocalizedMessage()); ? ? } } // this.response就是拋出原來的結果,就比如你寫的邏輯沒有成功攔截到500狀態(tài)碼的其他異常,是啥就顯示啥 return this.response; }
這樣就完成實現(xiàn)攔截到thymeleaf的異常,@ControllerAdvice處理不了的異??梢允褂肊rrorController來處理,耶穌也攔不住,魯某說的
有很多東西是后知后覺的,一年前我可能不知道怎么處理,只能去處理業(yè)務,避免出現(xiàn)這種異常,時間久了,好多知識點就慢慢領悟了。(多動手)
到此這篇關于淺談SpringBoot如何正確攔截thymeleaf異常的文章就介紹到這了,更多相關SpringBoot攔截thymeleaf異常內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java調用高德地圖API根據(jù)詳細地址獲取經(jīng)緯度詳細教程
寫了一個經(jīng)緯度相關的工具,分享給有需求的小伙伴們,下面這篇文章主要給大家介紹了關于Java調用高德地圖API根據(jù)詳細地址獲取經(jīng)緯度,文中通過圖文以及代碼介紹的非常詳細,需要的朋友可以參考下2024-04-04springboot整合websocket實現(xiàn)群聊思路代碼詳解
通過springboot引入websocket,實現(xiàn)群聊,通過在線websocket測試進行展示。本文重點給大家介紹springboot整合websocket實現(xiàn)群聊功能,代碼超級簡單,感興趣的朋友跟隨小編一起學習吧2021-05-05springboot學習筆記之 profile多環(huán)境配置切換的實現(xiàn)方式
這篇文章主要介紹了springboot profile多環(huán)境配置切換的實現(xiàn)方式,本文給大家介紹的非常詳細,具有一定的參考借鑒價值 ,需要的朋友可以參考下2019-07-07