1.定義異常接口安全
public interface ResultCode {
boolean success();
int code();
String msg();
}
2.定義異常枚舉ide
@ToString
public enum CommonCode implements ResultCode {
SUCCESS(true,200,"請求成功!"),
FAILED(false,9999,"請求失敗!"),
INVALID_PARAM(false,9001,"非法入參!");
boolean success;
int code;
String msg;
CommonCode(boolean success, int code, String msg) {
this.success = success;
this.code = code;
this.msg = msg;
}
@Override
public boolean success() {
return success;
}
@Override
public int code() {
return code;
}
@Override
public String msg() {
return msg;
}
}
3.返回基本數據類型ui
public class ResponseResult{
private boolean success;
private int code;
private String message;
private Object data;
public ResponseResult(){}
public ResponseResult(boolean success, int code, String message, Object data) {
this.success = success;
this.code = code;
this.message = message;
this.data = data;
}
public ResponseResult(ResultCode resultCode) {
this.success = resultCode.success();
this.code = resultCode.code();
this.message = resultCode.msg();
}
//getter setter
}
4.自定義異常this
public class CustomException extends RuntimeException {
private ResultCode resultCode;
public ResultCode getResultCode() {
return resultCode;
}
public CustomException(ResultCode resultCode) {
//異常信息爲錯誤代碼+異常信息(自定義咱們的異常信息格式)
this.resultCode = resultCode;
}
}
5.異常轉化spa
public class ExceptionCast {
public static void cast(ResultCode resultCode){
throw new CustomException(resultCode);
}
}
6.異常統一處理線程
@ControllerAdvice
public class ExceptionCatch {
//捕獲 CustomException異常
@ExceptionHandler(CustomException.class)
@ResponseBody
public ResponseResult customException(CustomException e) {
e.printStackTrace();
ResultCode resultCode = e.getResultCode();
ResponseResult rr = new ResponseResult(resultCode);
return rr;
}
//使用EXCEPTIONS存放異常類型和錯誤代碼映射 ImmutableMap的特色是一旦建立不可改變 而且線程安全
// 定義map 配置異常類型所對應的錯誤代碼
private static ImmutableMap<Class<? extends Throwable>, ResultCode> EXCEPTIONS;
//定義map的builder對象 去構建ImmutableMap對象
protected static ImmutableMap.Builder<Class<? extends Throwable>, ResultCode> builder = ImmutableMap.builder();
//使用build來構建一個y異常類型和錯誤代碼異常
@ExceptionHandler(Exception.class)
@ResponseBody
public ResponseResult exception(Exception e) {
e.printStackTrace();
if (EXCEPTIONS == null) {
EXCEPTIONS = builder.build(); //EXCEPTIONS構建成功
}
//從EXCEPTIONS中找異常類型所對因的錯誤代碼 若是找到了將錯誤代碼相應給用戶 若是找不到響應9999異常
ResultCode resultCode = EXCEPTIONS.get(e.getClass());
if (resultCode != null) {
return new ResponseResult(resultCode);
} else {
return new ResponseResult(CommonCode.FAILED);
}
}
static {
builder.put(HttpMessageNotReadableException.class, CommonCode.INVALID_PARAM);
}
}
7.SpringBoot起動掃面自定義切面類code
@SpringBootApplication
@ComponentScan(basePackages = {"exception","demo.controller"})public class ActivitiApplication { public static void main(String[] args) { SpringApplication.run(ActivitiApplication.class, args); }}