SpingBoot三:統一返回類與錯誤處理器ExceptionHandler

在上一個介紹中,Controlle層我們返回的數據類型各不一致,如果出現錯誤的話,還會返回一個錯誤頁面,這對請求很不友好,所以我們對返回結果做一個統一的包裝。

首先定義一個簡單的錯誤碼及錯誤信息的枚舉類:ResponseCodeConstant。

public enum ResponseCodeConstant {
    SUCCESS(200, "接口調用成功"),
    FAIL(300, "業務處理失敗"),
    PARAM_INPUT_INVALID(400, "參數校驗非法"),
    PARAM_ABNORMAL(401, "參數異常"),
    UNKNOW_SYSTEM_ERROR(500, "未知系統異常"),
    TIMEOUT(501, "後端接口調用超時");


    private int code;
    private String message;

    ResponseCodeConstant(int code, String message) {
        this.code = code;
        this.message = message;
    }


    public String toString() {
        return "Code: " + this.code + ";Messge: " + this.message;
    }

    public int getCode() {
        return this.code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return this.message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

自定義一個統一返回的基礎類:BaseResult。

public class BaseResult<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    private int code;
    private String msg;
    private T data;

    public static <T> BaseResult<T> success(T t) {
        BaseResult<T> rst = new BaseResult<>();
        rst.setCode(ResponseCodeConstant.SUCCESS.getCode());
        rst.setData(t);
        return rst;
    }

    public static <T> BaseResult<T> fail(ResponseCodeConstant responseCodeConstants) {
        return fail(responseCodeConstants, null);
    }

    public static <T> BaseResult<T> fail(String msg) {
        BaseResult<T> rst = new BaseResult<>();
        rst.setMsg(msg);
        rst.setCode(ResponseCodeConstant.FAIL.getCode());
        return rst;
    }

    public static <T> BaseResult<T> fail(ResponseCodeConstant responseCodeConstant, String msg) {
        BaseResult<T> rst = new BaseResult<>();
        if (StringUtils.isNotBlank(msg)) {
            rst.setMsg(msg);
        } else {
            rst.setMsg(responseCodeConstant.getMessage());
        }
        rst.setCode(responseCodeConstant.getCode());
        return rst;
    }

    public static <T> BaseResult<T> fail(int code, String msg) {
        BaseResult<T> rst = new BaseResult<>();
        rst.setMsg(msg);
        rst.setCode(code);
        return rst;
    }

    public boolean isSuccess(){
        return this.code == ResponseCodeConstant.SUCCESS.getCode();
    }


    public void setCode(int code) {
        this.code = code;
    }

    public int getCode() {
        return this.code;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public String getMsg() {
        return this.msg;
    }

    public T getData() {
        return this.data;
    }

    public void setData(T data) {
        this.data = data;
    }
    
}

定義一個錯誤類:BaseException

public class BaseException extends RuntimeException {

    private int errCode;

    public int getErrCode() {
        return errCode;
    }

    public void setErrCode(int errCode) {
        this.errCode = errCode;
    }

    private BaseException() {
        super();
    }

    public BaseException(String message) {
        super(message);
        this.errCode = ResponseCodeConstant.FAIL.getCode();
    }


    public BaseException(int errorCode, String message) {
        super(message);
        this.errCode = errorCode;
    }
}

接下來就是重點了,統一的異常捕獲處理類:ExceptionsHandler

import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

/**
 * @Author fusheng
 */
//處理全局異常
@RestControllerAdvice
@ResponseBody
public class ExceptionsHandler {

    @ExceptionHandler(NullPointerException.class)
    public BaseResult handleNPException(NullPointerException np) {
        return BaseResult.fail(ResponseCodeConstant.PARAM_ABNORMAL, "參數空異常");
    }

    @ExceptionHandler(IndexOutOfBoundsException.class)
    public BaseResult handleIndexException(IndexOutOfBoundsException e) {
        return BaseResult.fail(ResponseCodeConstant.PARAM_ABNORMAL, "選取長度過長=" + e.getMessage());
    }

    @ExceptionHandler(BindException.class)
    public BaseResult handleBindException(BindException e) {
        String msg = e.getAllErrors()
                .stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.joining(","));
        return BaseResult.fail(ResponseCodeConstant.PARAM_INPUT_INVALID, msg);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public BaseResult handleParamException(MethodArgumentNotValidException e) {
        String message = e.getBindingResult().getAllErrors()
                .stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.joining(","));
        return BaseResult.fail(ResponseCodeConstant.PARAM_INPUT_INVALID, message);
    }

    @ExceptionHandler(BaseException.class)
    public BaseResult handleBaseException(BaseException e) {
        return BaseResult.fail(e.getErrCode(), e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public BaseResult handleException(Exception e){
        return BaseResult.fail(e.getMessage());
    }

}
@RestControllerAdvice相當於@ControllerAdvice+@ResponseBody註解,用來捕獲項目的全局異常,並返回。
@ExceptionHandler用來指定要捕獲的異常,可以是多個。@ExceptionHandler({NullPointerException.class,IllegalArgumentException.class})

雖然上面的例子中捕獲NP和越界異常,但在實際開發中要儘量避免拋出這種異常,要對可能爲null的數據進行判斷,截取數組,集合或者字符串的時候要根據長度做一下控制。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章