Spring Boot 進階之Web進階 學習 - 統一異常處理

1.新建返回結果類 result.javajava

public class Result<T> {

//錯誤碼
private Integer code;
//提示信息
private String msg;
//具體內容
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.自定義異常處理類 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.新建服務 GirlService.java 拋出異常
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);  //定義枚舉,統一管理
}else if (age >10 && age <16){
throw new GirlException(ResultEnum.MIDDLE_SCHOOL);
}

}

4.controller類中調用girlService.getAge(id)方法,並拋出異常
@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,"未知錯誤"),    SUCCESS(0,"成功"),    PRIMARY_SCHOOL(100,"你可能還在上小學"),    MIDDLE_SCHOOL(101,"你可能在上初中")    ;    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;    }}
相關文章
相關標籤/搜索