定义枚举类
public enum ResultEnum {
PRIMARY_SCHOOL(100, "你可能在上小学"),
MIDDLE_SCHOLL(101, "你可能在上中学"),
;
private Integer code;
private String message;
ResultEnum(Integer code, String message) {
this.code = code;
this.message = message;
}
public Integer getCode() {
return code;
}
public String getMessage() {
return message;
}
}
在抛出异常中使用枚举类型
@Service
public class GirlService {
@Autowired
private GirlRepository girlRepository;
public void getAge(Integer id){
Girl girl = girlRepository.findById(id).get();
Integer age = girl.getAge();
if (age <= 10) {
throw new GirlException(ResultEnum.PRIMARY_SCHOOL);
}
if (age < 16) {
throw new GirlException(ResultEnum.MIDDLE_SCHOLL);
}
}
}
异常处理类中接受枚举类型
public class GirlException extends RuntimeException {
private Integer code;
public GirlException(ResultEnum resultEnum){
super(resultEnum.getMessage());
this.code = resultEnum.getCode();
}
public Integer getCode() {
return code;
}
public void setCode(Integer code){
this.code = code;
}
}