SpringBoot中@RestControllerAdvice 全局異常處理的實現(xiàn)
利用注解@RestControllerAdvice 輕輕松松實現(xiàn)全局異常處理
一、定義統(tǒng)一響應體
package com.zhh.demo.common.response; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import java.io.Serializable; /** * @Description: 接口出參統(tǒng)一響應實體 * @Author: zhaoheng * @CreateTime: 2022-08-05 16:27 */ @Data @ApiModel("接口出參統(tǒng)一響應實體") public class Response<T> implements Serializable { private static final long serialVersionUID = 3692286106860121474L; @ApiModelProperty(value = "狀態(tài)碼") private String code; @ApiModelProperty(value = "說明") private String message; private T data; public Response(){} public Response(String code, String message) { this.code = code; this.message = message; } public Response(String code, String message, T data) { this.code = code; this.message = message; this.data = data; } }
package com.zhh.demo.common.response; import lombok.Getter; /** * @Description: 統(tǒng)一響應code和說明 * @Author: zhaoheng * @CreateTime: 2022-08-05 16:42 */ public enum ResponseCode { /** 通用碼 **/ FAIL("-1", "系統(tǒng)錯誤"), OK("200", "成功"), /** * 參考阿里巴巴開發(fā)手冊 * 錯誤碼為字符串類型,共5位,分兩部分組成:錯誤標識+4位數(shù)字編號。 * 例:A0001,A1001,B0001,C0001... A、B、分別代表不通業(yè)務或者來源 **/ /** 參數(shù)校驗不通過 **/ PARAMETER_CHECK_FAILS("A0001","參數(shù)校驗不通過"), /** 用戶相關 A1xxx **/ USER_NAME_NONSTANDARD("A1002", "用戶名不合規(guī)"); ResponseCode(String code, String msg) { this.code = code; this.msg = msg; } @Getter private String code; @Getter private String msg; }
package com.zhh.demo.common.response; import com.zhh.demo.entity.common.ResponsePage; import java.util.List; /** * @Description: 接口統(tǒng)一響應實體構造類 * @Author: zhaoheng * @CreateTime: 2022-08-05 16:37 */ public class ResponseFactory { /** * 默認成功 * @param t * @param <T> * @return */ public static <T> Response<T> success(T t){ return new Response<T>(ResponseCode.OK.getCode(),ResponseCode.OK.getMsg(),t); } /** * 成功 * @param responseCode 響應code和說明 * @param t * @param <T> * @return */ public static <T> Response<T> success(ResponseCode responseCode, T t){ return new Response<T>(responseCode.getCode(),responseCode.getMsg(),t); } /** * 成功 * @param responseCode 響應code和說明 * @return */ public static <T> Response<T> success(ResponseCode responseCode){ return new Response<T>(responseCode.getCode(),responseCode.getMsg()); } /** * 默認失敗 * @param <T> * @return */ public static <T> Response<T> error(){ return new Response<T>(ResponseCode.FAIL.getCode(),ResponseCode.FAIL.getMsg()); } /** * 失敗 * @param responseCode 響應code和說明 * @param t * @param <T> * @return */ public static <T> Response<T> error(ResponseCode responseCode, T t){ return new Response<T>(responseCode.getCode(),responseCode.getMsg(),t); } /** * 失敗 * @param responseCode 響應code和說明 * @return */ public static <T> Response<T> error(ResponseCode responseCode){ return new Response<T>(responseCode.getCode(),responseCode.getMsg()); } /** * 失敗 * @param code 錯誤碼 * @param msg 說明 * @param t 響應數(shù)據(jù) * @param <T> * @return */ public static <T> Response<T> error(String code, String msg, T t){ return new Response<T>(code,msg,t); } /** * 失敗 * @param code 錯誤碼 * @param msg 說明 * @return */ public static <T> Response<T> error(String code, String msg){ return new Response<T>(code,msg); } public static <T> ResponsePage pageResult(List<T> list, int total){ return new ResponsePage<T>(list,total); } }
二、定義全局異常處理類
package com.zhh.demo.common.exception; import com.zhh.demo.common.response.Response; import com.zhh.demo.common.response.ResponseCode; import com.zhh.demo.common.response.ResponseFactory; import lombok.extern.slf4j.Slf4j; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import java.util.List; /** * @Description: 全局異常處理 * @Author: zhaoheng * @CreateTime: 2022-08-05 17:33 */ @Slf4j @RestControllerAdvice public class ExceptionHandle { /** * 處理Exception異常 * @param exception 異常類型 * @return */ @ExceptionHandler(value = Exception.class) public Response<?> ExceptionHandle(Exception exception){ log.error("系統(tǒng)出現(xiàn)異常:",exception); return ResponseFactory.error(ResponseCode.FAIL); } /** * 處理業(yè)務異常 * @param exception 異常類型 * @return */ @ExceptionHandler(value = BaseException.class) public Response<?> BaseExceptionHandle(BaseExceptionexception){ log.error("系統(tǒng)業(yè)務異常:",exception); return ResponseFactory.error(exception.getCode(),exception.getMsg()); } /** * 入?yún)⑿r灝惓?,校驗不通過,拋出異常信息 * @param exception Valid 入?yún)⑿r灝惓? * @return */ @ExceptionHandler(value = MethodArgumentNotValidException.class) public Response<?> methodArgumentNotValidExceptionHandle(MethodArgumentNotValidException exception){ log.error("入?yún)⑿r灢煌ㄟ^",exception); BindingResult bindingResult = exception.getBindingResult(); List<FieldError> fieldErrorList = bindingResult.getFieldErrors(); fieldErrorList.forEach(fieldError -> { log.info("字段:{},message:{}",fieldError.getField(),fieldError.getDefaultMessage()); }); // 一個一個給調用方返回提示 String message = fieldErrorList.get(0).getDefaultMessage(); return ResponseFactory.error(ResponseCode.PARAMETER_CHECK_FAILS.getCode(), message); } }
自定義異常
package com.zhh.demo.common.exception; import com.zhh.demo.common.response.Response; import com.zhh.demo.common.response.ResponseCode; import lombok.Data; /** * @Description: 異?;? * @Author: zhaoheng * @CreateTime: 2022-08-05 17:22 */ @Data public abstract class BaseException extends RuntimeException{ /** * code碼 */ private String code; /** * 異常說明 */ private String msg; /** * 響應體 */ private Response response; public BaseException(String code, String msg) { super(msg); this.code = code; this.msg = msg; this.response = new Response(code,msg); } public BaseException(ResponseCode responseCode) { super(responseCode.getMsg()); this.code = responseCode.getCode(); this.msg = responseCode.getMsg(); this.response = new Response(responseCode.getCode(),responseCode.getMsg()); } }
三、編寫接口測試效果
package com.zhh.demo.controller; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; @Api(tags = "test-api") @RequestMapping("/api/test") @RestController @Validated // 開啟入?yún)⑿r? public class TestController { @ApiOperation("異常測試") @PostMapping("/t1") public String test(){ // 模擬異常 new ArrayList<>().get(1); return ""; } }
經(jīng)過測試,接口拋出異常后會被異常處理類處理,并且給調用端返回指定格式的提示信息
{ "code": "-1", "message": "系統(tǒng)錯誤", "data": null }
到此這篇關于SpringBoot中@RestControllerAdvice 全局異常處理的實現(xiàn)的文章就介紹到這了,更多相關SpringBoot @RestControllerAdvice 全局異常內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
- SpringBoot中@RestControllerAdvice注解實現(xiàn)全局異常處理類
- springboot的統(tǒng)一異常處理,使用@RestControllerAdvice詳解
- SpringBoot項目中@RestControllerAdvice全局異常失效問題的解決
- SpringBoot中@RestControllerAdvice @ExceptionHandler異常統(tǒng)一處理類失效原因分析
- SpringBoot中@RestControllerAdvice注解的使用
- SpringBoot的@RestControllerAdvice作用詳解
- SpringBoot常用注解@RestControllerAdvice詳解
- SpringBoot中的@RestControllerAdvice注解詳解
- SpringBoot?@RestControllerAdvice注解對返回值統(tǒng)一封裝的處理方法
相關文章
Springboot初始化啟動報錯Error?creating?bean?with?name?'da
這篇文章主要為大家介紹了Springboot初始化啟動報Error?creating?bean?with?name?'dataSource'?defined?in?class?path?resource解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-08-08教你用java完美封裝微信模板消息的發(fā)送動態(tài)
這篇文章主要介紹了教你用java完美封裝微信模板消息的發(fā)送動態(tài),文中有非常詳細的代碼示例,對正在學習java的小伙伴們有很好的幫助,需要的朋友可以參考下2021-04-04一小時迅速入門Mybatis之實體類別名與多參數(shù) 動態(tài)SQL
這篇文章主要介紹了一小時迅速入門Mybatis之實體類別名與多參數(shù) 動態(tài)SQL,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-09-09Mybatis resultType返回結果為null的問題排查方式
這篇文章主要介紹了Mybatis resultType返回結果為null的問題排查方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03