捕獲全局異常——@ControllerAdvice
因爲本文講述的是捕獲全局異常,通過閱讀官方文檔,@ControllerAdvice註解的默認行爲(即,如果不使用任何選擇器使用),帶@ControllerAdvice註釋的類將幫助所有已知的Controller。因此,本文不帶上任何參數設置,有興趣的可以查看官方文檔
編寫捕獲異常代碼(因爲是編寫API,所以這裏返回的都是數據)
import com.jian.Result.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* 統一處理異常
*
* @author YeZhiJian
*
*/
@org.springframework.web.bind.annotation.ControllerAdvice
@ResponseBody
public class ControllerAdvice {
private final static Logger logger = LoggerFactory.getLogger(ControllerAdvice.class);
/**
* 統一捕獲異常
* @param e
* @return Result只是自定義的統一返回數據
*/
@ExceptionHandler(Exception.class)
public Result<String> ExceptionHandler(Exception e){
logger.error("------------------------------------------------異常捕獲----------------------------------------");
logger.error("異常類型 : " + e.getClass());
logger.error("異常信息 : " + e.getLocalizedMessage());
e.printStackTrace();
logger.error("------------------------------------------------------------------------------------------------");
return Result.failure(ExceptionTypeMap.getExceptionTypeReturn(e.getClass()));
}
}
編寫統一獲取的常見異常以及統一返回
import java.util.HashMap;
import java.util.Map;
/**
* 異常返回
*
* @author YeZhiJian
*
*/
public class ExceptionTypeMap {
/**
* 定義一個Map,用於判斷異常的返回值
*/
private static Map<Class<? extends Exception>, String> throwableMap = new HashMap<>();
/**
* 靜態塊中初始化自定義異常類型返回
*/
static {
throwableMap.put(ArrayIndexOutOfBoundsException.class, "數組下標越界,請稍後再試");
throwableMap.put(NullPointerException.class, "空指針異常,請稍後再試");
throwableMap.put(ClassNotFoundException.class, "指定的類不存在異常,請稍後再試");
throwableMap.put(ArithmeticException .class, "數學運算異常,請稍後再試");
throwableMap.put(IllegalAccessException.class, "接口調取沒有訪問權限,請稍後再試");
throwableMap.put(ClassCastException.class, "類型轉換異常,請稍後再試");
throwableMap.put(IllegalArgumentException.class, "非法參數異常,請稍後再試");
throwableMap.put(NumberFormatException.class, "數字格式化異常,請稍後再試");
throwableMap.put(java.text.ParseException.class, "解析異常,請稍後再試");
throwableMap.put(ArrayStoreException.class, "數組存儲異常,請稍後再試");
}
/**
* 獲取返回值
* @return
*/
public static String getExceptionTypeReturn (Class<? extends Exception> exceptionClass){
if (throwableMap.containsKey(exceptionClass)){
return throwableMap.get(exceptionClass);
}
// 通用返回
return "遇到預期之外的錯誤,請稍後再試";
}
}