public class CustomException extends RuntimeException implements java.io.Serializable {
private int code;
private String message;
/**
* 统一异常消息处理
*
* @param exceptionEnum 异常枚举值
*/
public CustomException(ExceptionEnum exceptionEnum) {
this.message = exceptionEnum.getValue();
}
/**
* 自定义异常消息处理
*
* @param code
* @param message
*/
public CustomException(int code, String message) {
this.code = code;
this.message = message;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
自定义异常枚举
public enum ExceptionEnum implements IEnum{
SYSTEM_EXCEPTION(100, "系统异常"),
UNKNOWN_EXCEPTION(101, "未知异常");
private int code;
private String message;
ExceptionEnum(int code, String message) {
this.code = code;
this.message = message;
}
@Override
public Integer getKey() {
return this.code;
}
@Override
public String getValue() {
return this.message;
}
}
将参数反序列化成枚举
public interface IEnum {
/**
* 获取枚举的key
*/
Integer getKey();
/**
* 获取枚举的下标
*/
String getValue();
/**
* 将参数反序列化为枚举
*
* @param param 当前值
* @param clazz 枚举类型
*/
static <T extends Enum<T> & IEnum> T parse(Integer param, Class<T> clazz) {
if (param == null || clazz == null) {
return null;
}
T[] enums = clazz.getEnumConstants();
for (T t : enums) {
Integer key = t.getKey();
if (key.equals(param)) {
return t;
}
}
return null;
}
}
实际使用
throw new CustomException(ExceptionEnum.UNKNOWN_EXCEPTION);// new一个自己的异常类