springboot搞定全局自定義異常


前言:

  SpringBoot的項目已經對有一定的異常處理了,但是對於我們開發者而言可能就不太合適了,因此我們需要對這些異常進行統一的捕獲並處理。SpringBoot中有一個ControllerAdvice的注解,使用該注解表示開啟了全局異常的捕獲,我們只需在自定義一個方法使用ExceptionHandler注解然后定義捕獲異常的類型即可對這些捕獲的異常進行統一的處理。

最終結果:

 

 

自定義基礎接口類

定義一個基礎的接口類,自定義的錯誤描述枚舉類需實現該接口。
代碼如下:

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

/** 錯誤描述*/
String getMsg();
}

自定義枚舉類

然后自定義一個枚舉類,並實現該接口。
代碼如下:

 
        

import lombok.Getter;

@Getter
public enum ErrorCodeAndMsg implements BaseErrorInfoInterface{
SUCCESS("200", "成功!"),
BODY_NOT_MATCH("400","請求的數據格式不符!"),
SIGNATURE_NOT_MATCH("401","請求的數字簽名不匹配!"),
NOT_FOUND("404", "未找到該資源!"),
INTERNAL_SERVER_ERROR("500", "服務器內部錯誤!"),
SERVER_BUSY("503","服務器正忙,請稍后再試!"),
STUDENG_NULL("0003", "學號不能為空");
private String code;
private String msg;
ErrorCodeAndMsg(String code, String msg) {
this.code = code;
this.msg = msg;
}

public String getCode() {
return code;
}
public String getMsg() {
return msg;
}
}

自定義異常類

定義一個異常類,用於處理我們發生的業務異常。
代碼如下:

import lombok.Getter;

/**
* 統一異常捕獲類
* Created by Tiger on 2018/10/9.
*/
@Getter
public class StudentException extends RuntimeException{
private String code;
private String msg;
public StudentException() {
super();
}

public StudentException(BaseErrorInfoInterface errorInfoInterface) {
super(errorInfoInterface.getCode());
this.code = errorInfoInterface.getCode();
this.msg = errorInfoInterface.getMsg();
}

public StudentException(BaseErrorInfoInterface errorInfoInterface, Throwable cause) {
super(errorInfoInterface.getCode(), cause);
this.code = errorInfoInterface.getCode();
this.msg = errorInfoInterface.getMsg();
}

public StudentException(String errorMsg) {
super(errorMsg);
this.msg = errorMsg;
}

public StudentException(String errorCode, String errorMsg) {
super(errorCode);
this.code = errorCode;
this.msg = errorMsg;
}

public StudentException(String errorCode, String errorMsg, Throwable cause) {
super(errorCode, cause);
this.code = errorCode;
this.msg = errorMsg;
}


public String getErrorCode() {
return code;
}

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

public String getErrorMsg() {
return msg;
}

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

public String getMessage() {
return msg;
}

@Override
public Throwable fillInStackTrace() {
return this;
}
}

自定義數據格式

順便這里定義一下數據的傳輸格式。
代碼如下:

 
        
public class ResultBody {
/**
* 響應代碼
*/
private String code;

/**
* 響應消息
*/
private String message;

/**
* 響應結果
*/
private Object result;

public ResultBody() {
}



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 Object getResult() {
return result;
}

public void setResult(Object result) {
this.result = result;
}

/**
* 成功
*
* @return
*/
public static ResultBody success() {
return success(null);
}

/**
* 成功
* @param data
* @return
*/
public static ResultBody success(Object data) {
ResultBody rb = new ResultBody();
rb.setCode(ErrorCodeAndMsg.SUCCESS.getCode());
rb.setMessage(ErrorCodeAndMsg.SUCCESS.getMsg());
rb.setResult(data);
return rb;
}

/**
* 失敗
*/
public static ResultBody error(BaseErrorInfoInterface errorInfo) {
ResultBody rb = new ResultBody();
rb.setCode(errorInfo.getCode());
rb.setMessage(errorInfo.getMsg());
rb.setResult(null);
return rb;
}

/**
* 失敗
*/
public static ResultBody error(String code, String message) {
ResultBody rb = new ResultBody();
rb.setCode(code);
rb.setMessage(message);
rb.setResult(null);
return rb;
}

/**
* 失敗
*/
public static ResultBody error( String message) {
ResultBody rb = new ResultBody();
rb.setCode("-1");
rb.setMessage(message);
rb.setResult(null);
return rb;
}

/*@Override
public String toString() {
return JSONObject.toJSONString(this);
}*/
}

自定義全局異常處理類

最后我們在來編寫一個自定義全局異常處理的類。
代碼如下:


@ControllerAdvice public class GlobalExceptionHandler { private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class); /** * 處理自定義的業務異常 * @param req * @param e * @return */ @ExceptionHandler(value = BizException.class) @ResponseBody public ResultBody bizExceptionHandler(HttpServletRequest req, BizException e){ logger.error("發生業務異常!原因是:{}",e.getErrorMsg()); return ResultBody.error(e.getErrorCode(),e.getErrorMsg()); } /** * 處理空指針的異常 * @param req * @param e * @return */ @ExceptionHandler(value =NullPointerException.class) @ResponseBody public ResultBody exceptionHandler(HttpServletRequest req, NullPointerException e){ logger.error("發生空指針異常!原因是:",e); return ResultBody.error(CommonEnum.BODY_NOT_MATCH); } /** * 處理其他異常 * @param req * @param e * @return */ @ExceptionHandler(value =Exception.class) @ResponseBody public ResultBody exceptionHandler(HttpServletRequest req, Exception e){ logger.error("未知異常!原因是:",e); return ResultBody.error(CommonEnum.INTERNAL_SERVER_ERROR); } }
控制層

 

 
        

業務層

 
        

 

 

 

 
        

 完成

原文地址:https://www.cnblogs.com/xuwujing/p/10933082.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM