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

定义枚举类

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;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容