全局異常捕獲和統(tǒng)一Json數(shù)據(jù)結(jié)構(gòu)返回

1.定義實(shí)體

1.1 錯(cuò)誤碼枚舉類

@Getter
public enum ErrorEnum {
    // 數(shù)據(jù)操作錯(cuò)誤定義
    SUCCESS(200, "成功"),
    NO_REQUEST(400,"請(qǐng)求無(wú)效"),
    NO_AUTH(401,"未授權(quán):登錄失敗"),
    NO_PERMISSION(403,"你沒(méi)得權(quán)限"),
    NOT_FOUND(404, "未找到該資源!"),
    INTERNAL_SERVER_ERROR(500, "服務(wù)器跑路了"),
    BUSINESS_ERROR(501, "客戶端業(yè)務(wù)異常"),
    ;
    /** 錯(cuò)誤碼 */
    private Integer errorCode;
    /** 錯(cuò)誤信息 */
    private String errorMsg;
    ErrorEnum(Integer errorCode, String errorMsg) {
        this.errorCode = errorCode;
        this.errorMsg = errorMsg;
    }

1.2 統(tǒng)一返回Json實(shí)體類

@Data
public class Result<T> {

    //是否成功
    private Boolean success;
    //狀態(tài)碼
    private Integer code;
    //提示信息
    private String msg;
    //數(shù)據(jù)
    private T data;
    public Result() {

    }
    
    public Result(Boolean success, Integer code, String msg, T data) {
        this.success = success;
        this.code = code;
        this.msg = msg;
        this.data = data;
    }
    /** 業(yè)務(wù)成功返回業(yè)務(wù)代碼,描述和返回的參數(shù) */
    public static <T> Result<T> success(T data) {
        return new Result<T>(true,ErrorEnum.SUCCESS.getErrorCode(),ErrorEnum.SUCCESS.getErrorMsg(),data);
    }

    //自定義異常返回的結(jié)果
    public static Result defineError(DefinitionException de){
        Result result = new Result();
        result.setSuccess(false);
        result.setCode(de.getErrorCode());
        result.setMsg(de.getErrorMsg());
        result.setData(null);
        return result;
    }
    //其他異常處理方法返回的結(jié)果
    public static Result otherError(ErrorEnum errorEnum){
        Result result = new Result();
        result.setMsg(errorEnum.getErrorMsg());
        result.setCode(errorEnum.getErrorCode());
        result.setSuccess(false);
        result.setData(null);
        return result;
    }

}

1.3 自定義異常實(shí)體類(提供兩個(gè)構(gòu)造方法)

@Data
public class DefinitionException extends RuntimeException {

    protected Integer errorCode;
    protected String errorMsg;

    /**
     * 自定義錯(cuò)誤碼和錯(cuò)誤描述
     * @param errorCode
     * @param errorMsg
     */
    public DefinitionException(Integer errorCode, String errorMsg) {
        this.errorCode = errorCode;
        this.errorMsg = errorMsg;
    }

    /**
     *  只指定錯(cuò)誤描述,不指定錯(cuò)誤碼
     * @param errorMsg
     */
    public DefinitionException(String errorMsg) {
        this.errorCode = errorCode;
        this.errorMsg = errorMsg;
    }

}

1.4 在提供一個(gè)可以業(yè)務(wù)使用的業(yè)務(wù)異常類

public class BusinessException extends DefinitionException {

    public BusinessException(Integer errorCode, String errorMsg) {
        super(errorCode, errorMsg);
    }

    public BusinessException(String errorMsg) {
        super(ErrorEnum.BUSINESS_ERROR.getErrorCode(),errorMsg);
    }

}

2.創(chuàng)建兩個(gè)處理器

2.1 全局異常處理器

@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 處理自定義異常
     *
     */
    @ExceptionHandler(value = DefinitionException.class)
    @ResponseBody
    public Result bizExceptionHandler(DefinitionException e) {
        return Result.defineError(e);
    }

    /**
     * 處理其他異常
     *
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result exceptionHandler( Exception e) {
        return Result.otherError(ErrorEnum.INTERNAL_SERVER_ERROR);
    }

2.2 統(tǒng)一Json返回處理器

@RestControllerAdvice
public class ResponseResultBodyAdvice implements ResponseBodyAdvice {
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (body instanceof Result){
            return body;
        }
        return Result.success(body);
    }

3.打包成start,這樣其他項(xiàng)目直接引入pom就可以使用了

3.1 創(chuàng)建一個(gè)配置類(將兩個(gè)處理器交給spring管理)

@Configuration
public class StarterAutoConfigure {

    @Bean
    public GlobalExceptionHandler globalExceptionHandler(){
        return new GlobalExceptionHandler();
    }

    @Bean
    public ResponseResultBodyAdvice responseResultBodyAdvice(){
        return new ResponseResultBodyAdvice();
    }
}

3.2 需要在resources目錄下新建一個(gè)META-INF的目錄,并創(chuàng)建一個(gè)spring.factories配置文件,并寫上下面的配置
注:第一行是固定的,第二行是配置類的地址

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.example.springbootdemo02.StarterAutoConfigure

4.大功告成,我們?cè)诹硗鈧€(gè)項(xiàng)目引入試一下

4.1 測(cè)試一下正常返回

    @GetMapping("result")
    public User result(){
        User user = new User();
        user.setId(886);
        user.setName("張三");
        return user;
    }

  輸出結(jié)果:
{
    "success": true,
    "code": 200,
    "msg": "成功",
    "data": {
        "id": 886,
        "name": "張三"
    }
}

4.2 再試一下系統(tǒng)發(fā)生異常的情況

@GetMapping("result")
   public User result(){
       User user = new User();
       user.setId(886);
       user.setName("張三");
       // 這里會(huì)報(bào)數(shù)學(xué)計(jì)算錯(cuò)誤異常
       Integer a = 1/0;
       return user;
   }
輸出結(jié)果:
{
   "success": false,
   "code": 500,
   "msg": "服務(wù)器跑路了",
   "data": null
}

4.3 試試業(yè)務(wù)異常的情況

@GetMapping("result")
    public User result(){
        User user = new User();
        user.setId(886);
        user.setName("張三");
        if (user.getId() > 100){
            throw new BusinessException("年齡大于100啦...");
        }
        return user;
    }
輸出結(jié)果:
{
    "success": false,
    "code": 501,
    "msg": "年齡大于100啦...",
    "data": null
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容