Spring Boot 进阶之Web进阶 学习 - 统一异常处理
1.新建返回结果类 result.java
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;
}
}