1. 程式人生 > >SpringBoot全域性異常捕獲及處理(包括自定義異常捕獲處理)

SpringBoot全域性異常捕獲及處理(包括自定義異常捕獲處理)

在做專案的時候需要對自定義異常做捕獲和處理,現在將程式碼記錄下來便於以後查閱。

1、全域性異常捕捉處理

@ControllerAdvice(
    annotations = {RestController.class}
)
public class ExceptionHandlerAdvice {
    
    private Logger logger = LoggerFactory.getLogger(this.getCLass());
    
    @ExceptionHandler(EntityTransException.class)
    public ResponseResult entityTransExceptionHandle(HttpServletRequest request,EntityTransException e){
        logger.error("********************Throw EntityTransException.url:{} ERROR:{}********************",request.getRequestURL(), e.getMessage(), e);
        ResponseResult result = new ResponseResult();
        result.setSuccess(false);
        result.setMessage(ResultCode.ERROR_ENTITY_TRANS.getMessage() + "。異常原因:" + e.getMessage());
        result.setCode(ResultCode.ERROR_ENTITY_TRANS.getCode());
        return result;
    }

    @ExceptionHandler(SqlException.class)
    public ResponseResult sqlExceptionHandle(HttpServletRequest request,SqlException e){
        logger.error("********************Throw SqlException.url:{} ERROR:{}********************",request.getRequestURL(), e.getMessage(), e);
        ResponseResult result = new ResponseResult();
        result.setSuccess(false);
        result.setMessage(ResultCode.ERROR_SQL_CHECK.getMessage() + "。異常原因:" + e.getMessage());
        result.setCode(ResultCode.ERROR_SQL_CHECK.getCode());
        return result;
    }

    @ExceptionHandler(Exception.class)
    public ResponseResult exceptionHandle(HttpServletRequest request,Exception e){
        logger.error("********************Throw Exception.url:{} ERROR:{}********************",request.getRequestURL(), e.getMessage(), e);
        ResponseResult result = new ResponseResult();
        result.setSuccess(false);
        result.setMessage(ResultCode.ERROR.getMessage());
        result.setCode(ResultCode.ERROR.getCode());
        return result;
    }

}

2、自定義異常類

package com.czgo.exception;
 
/**
 * 自定義異常類(繼承執行時異常)
 * @author zhangzhixiang
 * @version 2018/11/09
 */
public class SqlException extends RuntimeException {
 
    private static final long serialVersionUID = 1L;
 
    /**
     * 錯誤編碼
     */
    private String errorCode;
 
    /**
     * 訊息是否為屬性檔案中的Key
     */
    private boolean propertiesKey = true;
     
    /**
     * 構造一個基本異常.
     *
     * @param cause 異常資訊
     *            
     */
    public SqlException(Throwable cause)
    {
        super(cause);
    }

    /**
     * 構造一個基本異常.
     *
     * @param message 資訊描述
     *            
     */
    public SqlException(String message)
    {
        super(message);
    }
 
    /**
     * 構造一個基本異常.
     *
     * @param errorCode 錯誤編碼
     * @param message 資訊描述
     *            
     */
    public SqlException(String errorCode, String message)
    {
        this(errorCode, message, true);
    }
 
    /**
     * 構造一個基本異常.
     *
     * @param errorCode 錯誤編碼
     * @param message 
     *                 
     */
    public SqlException(String errorCode, String message, Throwable cause)
    {
        this(errorCode, message, cause, true);
    }
 
    /**
     * 構造一個基本異常.
     *
     * @param errorCode 錯誤編碼
     * @param message 資訊描述
     * @param propertiesKey 訊息是否為屬性檔案中的Key
     *            
     */
    public SqlException(String errorCode, String message, boolean propertiesKey)
    {
        super(message);
        this.setErrorCode(errorCode);
        this.setPropertiesKey(propertiesKey);
    }
 
    /**
     * 構造一個基本異常.
     *
     * @param errorCode 錯誤編碼
     * @param message 資訊描述
     *            
     */
    public SqlException(String errorCode, String message, Throwable cause, boolean propertiesKey)
    {
        super(message, cause);
        this.setErrorCode(errorCode);
        this.setPropertiesKey(propertiesKey);
    }
 
    /**
     * 構造一個基本異常.
     *
     * @param message 資訊描述
     * @param cause 根異常類(可以存入任何異常)
     *            
     */
    public SqlException(String message, Throwable cause)
    {
        super(message, cause);
    }
    
    public String getErrorCode()
    {
        return errorCode;
    }
 
    public void setErrorCode(String errorCode)
    {
        this.errorCode = errorCode;
    }
 
    public boolean isPropertiesKey()
    {
        return propertiesKey;
    }
 
    public void setPropertiesKey(boolean propertiesKey)
    {
        this.propertiesKey = propertiesKey;
    }
    
}

3、Controller層

@RestController
@RequestMapping("/user")
public class FileController extends ExceptionHandlerAdvice {
    
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @RequestMapping(value = "/selectByCondition", method = RequestMethod.POST)
    public ResponseResult selectByCondition() throws Exception {
        throw new EntityTransException("這是一個自定義實體轉換異常,這條異常會在ExceptionHandlerAdvice的entityTransExceptionHandle方法中被攔截");
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public ResponseResult update() throws Exception {
        throw new SqlException("這是一個自定義SQL異常,這條異常會在ExceptionHandlerAdvice的sqlExceptionHandle方法中被攔截");
    }

}

4、封裝返回實體

public class ResponseResult implements Serializable {
    
    private static final long serialVersionUID = 6054052582421291408L;
    
    private String message;
    private Object data;
    private int code;
    private boolean success;
    private Long total;

    public ResponseResult(){}

    public ResponseResult(boolean success, Object data) {
        this.success = success;
        this.data = data;
    }

    public ResponseResult(boolean success, String message, Object data) {
        this.success = success;
        this.message = message;
        this.data = data;
    }

    public String getMessage() {
        return message;
    }

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

    public Object getData() {
        return data;
    }

    public ResponseResult setData(Object data) {
        this.data = data;
        return this;
    }

    public boolean getSuccess() {
        return success;
    }

    public ResponseResult setSuccess(boolean success) {
        this.success = success;
        return this;
    }

    public int getCode() {
        return code;
    }

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

    public Long getTotal() {
        return success;
    }

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

}

全篇文章完全純手打,如果覺得對您有幫助,記得加關注給好評喲~~