1. Create a new return result class result.java
public class Result<T> {
//Error code
private Integer code;
//Prompt information
private String msg;
//Specific content
private T data;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this .code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this .data = data;
}
}
2. Custom exception handling class GirlException.java
public class GirlException extends RuntimeException{
private Integer code;
public GirlException(ResultEnum resultEnum){
super(resultEnum.getMsg());
this.code = resultEnum.getCode();
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
3. The new service GirlService.java throws an exception
public void getAge (Integer id) throws Exception {
Girl girl = girlReposistory.findById(id).get();
Integer age = girl.getAge();
if(age<10){
throw new GirlException ( ResultEnum.PRIMARY_SCHOOL ); / /Define enumeration, unified management
}else if (age >10 && age <16){
throw new GirlException ( ResultEnum.MIDDLE_SCHOOL );
}
}
4. The girlService.getAge(id) method is called in the controller class and an exception is thrown
@GetMapping(value = "/getage/{id}")
public void getAge(@PathVariable("id") Integer id) throws Exception{
girlService.getAge(id);
}
5.新建 ResultEnum.java枚举
public enum ResultEnum {
UNKONW_ERROR(-1,"unknown error"),
SUCCESS(0,"success"),
PRIMARY_SCHOOL(100,"you may still be in elementary school"),
MIDDLE_SCHOOL(101,"you may be in junior high school")
;
private Integer code;
private String msg;
ResultEnum(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public Integer getCode() {
return code;
}
public String getMsg() {
return msg;
}
}