異常統一處理
項目中有負責此方面,最近有空正好總結下,代碼爲測試代碼,非在項目中所寫的業務代碼,本質相同。
異常拋出及處理流程:
圖片百度得來,覺得總結的比較好。
1、在項目拋出自定義異常,springMVC框架拋出框架異常類型
2、統一由異常捕獲類捕獲異常,並進行處理
3、捕獲到自定義異常則直接取出錯誤代碼及錯誤信息,響應給用戶。
4、捕獲到非自定義異常類型首先從Map中找該異常類型是否對應具體的錯誤代碼,如果有則取出錯誤代碼和錯誤信息並響應給用戶,如果從Map中找不到異常類型所對應的錯誤代碼則統一爲404錯誤代碼並響應給用戶。
5、將錯誤代碼及錯誤信息以Json格式響應給用戶。
總結:一句話,捕獲的異常能解析則解析,不能解析則統一給個響應碼,此響應碼對應一個通用錯誤消息,比如“系統繁忙”,前端拿着此響應碼記得給個好點的圖,不然會被差評(哈哈哈)。
自定義異常類:
/**
* 描述:
* 自定義異常類
*
* @author XueGuCheng
* @create 2020-02-29 23:06
*/
public class XGCException extends RuntimeException {
private ResultCode resultCode;
public XGCException(ResultCode resultCode){
//異常信息爲錯誤代碼 + 異常信息
super("錯誤代碼:"+resultCode.code()+"錯誤信息:"+resultCode.message());
this.resultCode = resultCode;
}
public ResultCode getResultCode(){
return this.resultCode;
}
}
自定義異常拋出類:
/**
* 描述:
* 自定義異常拋出類
*
* @author XueGuCheng
* @create 2020-02-29 23:09
*/
public class ExceptionCast {
//使用此靜態方法拋出自定義異常
public static void cast(ResultCode resultCode){
throw new XGCException(resultCode);
}
}
自定義異常捕獲類:
/**
* 描述:
* 自定義異常捕獲類
*
* @author XueGuCheng
* @create 2020-02-29 23:12
*/
@ControllerAdvice
public class ExceptionCatch {
private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionCatch.class);
//使用ImmutableMap類型的容器存放異常類型和錯誤代碼的映射:EXCEPTIONS
//ImmutableMap的特點的一旦創建不可改變,並且線程安全
private static ImmutableMap<Class<? extends Throwable>, ResultCode> EXCEPTIONS;
//使用builder來構建一個異常類型和錯誤代碼的異常
protected static ImmutableMap.Builder<Class<? extends Throwable>, ResultCode> builder = ImmutableMap.builder();
//捕獲XGCException異常
@ExceptionHandler(XGCException.class)
@ResponseBody
public ResponseResult xGCException(XGCException e) {
LOGGER.error("catch exception : {}\r\nexception: ", e.getMessage(), e);
ResultCode resultCode = e.getResultCode();
ResponseResult responseResult = new ResponseResult(resultCode);
return responseResult;
}
//對Exception異常的捕獲
@ExceptionHandler(Exception.class)
@ResponseBody
public ResponseResult exception(Exception exception) {
//記錄日誌
LOGGER.error("catch exception:{}", exception.getMessage());
if (EXCEPTIONS == null) {
EXCEPTIONS = builder.build();
}
final ResultCode resultCode = EXCEPTIONS.get(exception.getClass());
final ResponseResult responseResult;
if (resultCode != null) {
responseResult = new ResponseResult(resultCode);
} else {
responseResult = new ResponseResult(CommonCode.SERVER_ERROR);
}
return responseResult;
}
static {
//在這裏加入一些基礎的異常類型判斷
builder.put(XXXException.class,Code);
}
}