美文网首页
SpringBoot 入门笔记(七)自定义枚举类型

SpringBoot 入门笔记(七)自定义枚举类型

作者: MonroeShen | 来源:发表于2019-02-08 13:41 被阅读0次

    定义枚举类

    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;
        }
    }
    

    相关文章

      网友评论

          本文标题:SpringBoot 入门笔记(七)自定义枚举类型

          本文链接:https://www.haomeiwen.com/subject/cfznsqtx.html