SpringBoot邏輯異常統一處理方法
阿新 • • 發佈:2020-01-07
這篇文章主要介紹了SpringBoot邏輯異常統一處理方法,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
構建專案
我們將邏輯異常核心處理部分提取出來作為單獨的jar供其他模組引用,建立專案在parent專案pom.xml新增公共使用的依賴,配置內容如下所示:
<dependencies> <!--Lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <!--測試模組依賴--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!--web依賴--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
專案建立完成後除了.idea、iml、pom.xml保留,其他的都刪除。
異常處理核心子模組
/** * @author WGR * @create 2019/9/7 -- 15:06 */ public class OssException extends RuntimeException implements Serializable { private static final long serialVersionUID = 1L; private Object[] errFormatArr; public OssException(String message,Object... obj) { super(message); this.errFormatArr = obj; } //由於實際需要,因此又追加以下兩種構造方法 public OssException(String message,Throwable cause) { super(message,cause); } public OssException(Throwable cause) { super(cause); } public Object[] getErrFormatArr() { return errFormatArr; } public void setErrFormatArr(Object[] errFormatArr) { this.errFormatArr = errFormatArr; } }
統一返回結果定義
@Slf4j @ControllerAdvice public class OssExceptionHandler { @ExceptionHandler(value = Exception.class) @ResponseBody public ModelAndView handle(Exception ex) { //使用FastJson提供的FastJsonJsonView檢視返回,不需要捕獲異常 FastJsonJsonView view = new FastJsonJsonView(); R result = null; if (ex instanceof OssException) {//自義異常 result = M.getErrR(ex.getMessage(),((OssException) ex).getErrFormatArr()); }else if(ex instanceof MaxUploadSizeExceededException) {//Spring的檔案上傳大小異常 result = M.getErrR("exception.maxUploadSizeExceededException",PropUtil.getInteger("upload.maxSize")); }else if(ex instanceof DataAccessException) {//Spring的JDBC異常 result = M.getErrR("exception.dataAccessException"); }else {//其他未知異常 result = M.keyErrR("exception.other"); } //開發過程中列印一下異常資訊,生產過程可關閉 if(result.getErrCode() != 60113) { //20181225 登陸會話失效,不列印了 String stackTrace = StackUtil.getStackTrace(ex); log.error("----->"+stackTrace); } //電腦端,封裝異常資訊 20181128 安全測試問題要求關閉詳細異常資訊 //if(WebUtil.isComputer()) result.setErrdetail(stackTrace); result.setErrdetail(ex.getMessage()); //20190128 異常資訊簡易的還需加入 view.setAttributesMap(result); return new ModelAndView(view); } }
由於種種原因,只能貼出部分程式碼,可以提供思路。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。