1. 程式人生 > 其它 >EurekaUser-返回型別和全域性異常

EurekaUser-返回型別和全域性異常

在專案裡面加入統一的返回資訊和異常處理

新建 檔案如下

public interface BaseErrorInfoInterface {
    /**
     * 錯誤碼
     */
    String getResultCode();

    /**
     * 錯誤描述
     */
    String getResultMsg();
}
public enum CommonEnum implements BaseErrorInfoInterface {

    // 資料操作錯誤定義
    BODY_NOT_MATCH("400", "請求的資料格式不符!"),
    SIGNATURE_NOT_MATCH(
"401", "請求的數字簽名不匹配!"), NOT_FOUND("404", "未找到該資源!"), INTERNAL_SERVER_ERROR("500", "伺服器內部錯誤!"), SERVER_BUSY("503", "伺服器正忙,請稍後再試!"); /** * 錯誤碼 */ private String resultCode; /** * 錯誤描述 */ private String resultMsg; CommonEnum(String resultCode, String resultMsg) {
this.resultCode = resultCode; this.resultMsg = resultMsg; } @Override public String getResultCode() { return resultCode; } @Override public String getResultMsg() { return resultMsg; } }
public class BizException extends RuntimeException{
    private
static final long serialVersionUID = 1L; /** * 錯誤碼 */ protected String errorCode; /** * 錯誤資訊 */ protected String errorMsg; public BizException() { super(); } public BizException(BaseErrorInfoInterface errorInfoInterface) { super(errorInfoInterface.getResultCode()); this.errorCode = errorInfoInterface.getResultCode(); this.errorMsg = errorInfoInterface.getResultMsg(); } public BizException(BaseErrorInfoInterface errorInfoInterface, Throwable cause) { super(errorInfoInterface.getResultCode(), cause); this.errorCode = errorInfoInterface.getResultCode(); this.errorMsg = errorInfoInterface.getResultMsg(); } public BizException(String errorMsg) { super(errorMsg); this.errorMsg = errorMsg; } public BizException(String errorCode, String errorMsg) { super(errorCode); this.errorCode = errorCode; this.errorMsg = errorMsg; } public BizException(String errorCode, String errorMsg, Throwable cause) { super(errorCode, cause); this.errorCode = errorCode; this.errorMsg = errorMsg; } public String getErrorCode() { return errorCode; } public void setErrorCode(String errorCode) { this.errorCode = errorCode; } public String getErrorMsg() { return errorMsg; } public void setErrorMsg(String errorMsg) { this.errorMsg = errorMsg; } public String getMessage() { return errorMsg; } @Override public Throwable fillInStackTrace() { return this; } }
@ControllerAdvice
public class GlobalExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 處理自定義的業務異常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    public BasicResult bizExceptionHandler(HttpServletRequest req, BizException e) {
        logger.error("發生業務異常e:{}", e.getMessage());
        return BasicResult.fail(e.getErrorCode(), e.getErrorMsg());
    }

    /**
     * 處理空指標的異常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public BasicResult exceptionHandler(HttpServletRequest req, NullPointerException e) {
        logger.error("發生空指標異常e:{}", e.getMessage());
        return BasicResult.fail(e.getMessage());
    }

    /**
     * 處理其他異常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public BasicResult exceptionHandler(HttpServletRequest req, Exception e) {
        logger.error("未知異常e:{}", e.getMessage());
        return BasicResult.fail(e.getMessage());
    }

    /**
     * 處理所有介面資料驗證異常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public BasicResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        logger.error("資料繫結異常e:{}", e.getMessage());
        return BasicResult.fail(e.getMessage());
    }

    /**
     * 請求型別異常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseBody
    public BasicResult httpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        logger.error("請求型別異常e:{}", e.getMessage());
        return BasicResult.fail(e.getMessage());
    }

    /**
     * 資料繫結異常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseBody
    public BasicResult missingServletRequestParameterException(MissingServletRequestParameterException e) {
        logger.error("資料繫結異常e:{}", e.getMessage());
        return BasicResult.fail(CommonEnum.BODY_NOT_MATCH.getResultMsg());
    }
}
public class BasicResult<T> {

    private T data;
    private Long total;
    public Boolean success;

    /**
     * 返回狀態碼
     */
    private String code;
    /**
     * 返回訊息
     */
    private String message;
    /**
     * 異常堆疊
     */
    private String fullStackTrace;

    private final static String SUCCESS_CODE = "0";
    private final static String DEFAULT_FAIL_CODE = "-1";

    public Boolean getSuccess() {
        return success;
    }

    public void setSuccess(Boolean success) {
        this.success = success;
    }

    public boolean isSuccess() {
        return Objects.equals(BasicResult.SUCCESS_CODE, this.code);
    }

    public String getCode() {
        return code;
    }

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

    public String getMessage() {
        return message;
    }

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

    public String getFullStackTrace() {
        return fullStackTrace;
    }

    public void setFullStackTrace(String fullStackTrace) {
        this.fullStackTrace = fullStackTrace;
    }

    public T getData() {
        return data;
    }

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

    public Long getTotal() {
        return total;
    }

    public void setTotal(Long total) {
        this.total = total;
    }


    /**
     * 成功
     *
     * @return
     */
    public static BasicResult success() {
        BasicResult basicResult = new BasicResult();
        basicResult.setCode(SUCCESS_CODE);
        return basicResult;
    }

    /**
     * 成功
     *
     * @param data
     * @param <T>
     * @return
     */
    public static <T> BasicResult<T> success(T data) {
        BasicResult<T> basicResult = new BasicResult<>();
        basicResult.setCode(SUCCESS_CODE);
        basicResult.setData(data);
        return basicResult;
    }

    /**
     * 成功
     *
     * @param data
     * @param message
     * @param <T>
     * @return
     */
    public static <T> BasicResult<T> success(T data, String message) {
        BasicResult<T> basicResult = new BasicResult<>();
        basicResult.setCode(SUCCESS_CODE);
        basicResult.setMessage(message);
        basicResult.setData(data);
        return basicResult;
    }

    /**
     * 成功
     *
     * @param data
     * @param <T>
     * @return
     */
    public static <T> BasicResult<T> success(T data, long total) {
        BasicResult<T> basicResult = new BasicResult<>();
        basicResult.setCode(SUCCESS_CODE);
        basicResult.setData(data);
        basicResult.setTotal(total);
        return basicResult;
    }

    /**
     * 成功
     *
     * @param data
     * @param message
     * @param <T>
     * @return
     */
    public static <T> BasicResult<T> success(T data, String message, Boolean success) {
        BasicResult<T> basicResult = new BasicResult<>();
        basicResult.setCode(SUCCESS_CODE);
        basicResult.setMessage(message);
        basicResult.setData(data);
        basicResult.setSuccess(success);
        return basicResult;
    }

    /**
     * 成功
     *
     * @param data
     * @param total
     * @param <T>
     * @return
     */
    public static <T> BasicResult<T> success(T data, Long total) {
        BasicResult<T> basicResult = new BasicResult<>();
        basicResult.setCode(SUCCESS_CODE);
        basicResult.setData(data);
        basicResult.setTotal(total);
        return basicResult;
    }

    /**
     * 失敗
     *
     * @param code
     * @param <T>
     * @return
     */
    static <T> BasicResult<T> fail(String code, Throwable throwable) {
        BasicResult<T> basicResult = new BasicResult<>();
        basicResult.setCode(code);
        basicResult.setMessage(throwable.getMessage());
        basicResult.setFullStackTrace(JSON.toJSONString(throwable));
        return basicResult;
    }

    /**
     * 失敗
     *
     * @param code
     * @param <T>
     * @return
     */
    public static <T> BasicResult<T> fail(String code, String message) {
        BasicResult<T> basicResult = new BasicResult<>();
        basicResult.setCode(code);
        basicResult.setMessage(message);
        return basicResult;
    }


    /**
     * 失敗
     *
     * @param message
     * @param <T>
     * @return
     */
    public static <T> BasicResult<T> fail(String message) {
        BasicResult<T> basicResult = new BasicResult<>();
        basicResult.setCode(DEFAULT_FAIL_CODE);
        basicResult.setMessage(message);
        return basicResult;
    }

    /**
     * 失敗
     *
     * @param throwable
     * @param <T>
     * @return
     */
    static <T> BasicResult<T> fail(Throwable throwable, Boolean isFull) {
        BasicResult<T> basicResult = new BasicResult<>();
        basicResult.setCode("500");
        basicResult.setMessage("系統出錯啦");
        if (isFull) {
            basicResult.setFullStackTrace(JSON.toJSONString(throwable));
        } else {
            basicResult.setFullStackTrace(throwable.getMessage());
        }
        return basicResult;
    }
}

其中需要對UserAction類進行改造,讓我們去訪問的時候會被對應的異常捕獲

@RestController
@RequestMapping("/user")
public class UserAction {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${server.port}")
    String port;

    @Resource
    private UserMapper userMapper;

    @PostMapping("/hi")
    public BasicResult<String> hi(@RequestParam String name) {
        logger.info("----- selectAll method test ------");
        List<User> userList = userMapper.selectList(null);
        logger.info("userList:{}", JSON.toJSON(userList));
        return BasicResult.success("hi " + name + ",i am from port:" + port);
    }

    @GetMapping("/getUser")
    public BasicResult<String> getUser(@RequestParam Integer name) {
        logger.info("----- selectAll method test ------");
        List<User> userList = userMapper.selectList(null);
        logger.info("userList:{}", JSON.toJSON(userList));
        return BasicResult.success("hi " + name + ",i am from port:" + port);
    }
}
BasicResult 是包裝的統一返回資訊。
GlobalExceptionHandler是程式異常的時候對異常的捕獲,然後返回對應的錯誤資訊。
BizException是自定義的系統異常。
啟動專案,瀏覽器訪問http://127.0.0.1:10001/user/hi

控制檯輸出如圖

異常會在HttpRequestMethodNotSupportedException進行處理,然後返回給使用者設定的統一的資料格式。

返回格式如下