要让不同情况返回不一样的异常提示
第一部:
新建一个输出异常的类继承RuntimeException,
package girl.girl.Exception;
public class GirlException extends RuntimeException {
private Integer code;
/*构造方法*/
public GirlException(Integer code,String message) {
super(message);
this.code = code;
}
/*get、set方法*/
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
然后在girlServiver类中将原来的Excetion类改为GirlException
public void getAge(Integer id) throws Exception{
Girl girl = girlRespository.findOne(id);
Integer age = girl.getAge();
if (age<10){
System.out.println(10);
//返回你还在上小学把把
throw new GirlException(100,"你还在上小学吧");
}else if (age >10 && age<16){
throw new GirlException(120,"你在上初中吧");
//返回你在上中学
}
}
在捕获异常的类中添加GIrlException情况添加进去
package girl.girl.ExceptionHandler;
import girl.girl.Exception.GirlException;
import girl.girl.domain.Result;
import girl.girl.util.ResultUtil;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
public class ExceptionHandler {
@org.springframework.web.bind.annotation.ExceptionHandler(value = Exception.class)
@ResponseBody
public Result hander(Exception e){
if (e instanceof GirlException){
GirlException girlException =(GirlException) e;
return ResultUtil.error(girlException.getCode(),girlException.getMessage());
}
return ResultUtil.error(110,e.getMessage());
}
}
上面代码中显示的异常的提示字眼,没有一个统一的管理比较混乱,
这个时候我们可以建一个枚举来统一的管理
第一步:建议枚举类
枚举类中不用set方法,需要get方法和构造函数
package girl.girl.enums;
import com.sun.corba.se.impl.interceptors.PICurrent;
public enum ResultEnums {
UNKOWN_ERROR(-1,"未知错误"),
SUCCESS(0,"成功"),
PRIMARY_SCHOOL(100,"你可能在上小学"),
MIDDLE_SCHOOL(120,"你可能在上中学"),
;
private Integer code;
private String msg;
ResultEnums(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public Integer getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
第二步:修改server类中的提示语改为枚举格式参数
修改前
修改后:
public void getAge(Integer id) throws Exception{
Girl girl = girlRespository.findOne(id);
Integer age = girl.getAge();
if (age<10){
System.out.println(10);
//返回你还在上小学把把
throw new GirlException(ResultEnums.PRIMARY_SCHOOL);
}else if (age >10 && age<16){
throw new GirlException(ResultEnums.MIDDLE_SCHOOL);
//返回你在上中学
}
}
由于GirlException这个类的参数还没改,上面的操作会飘红,
第三步骤:修改一下GirlException类的参数
修改前
修改后
package girl.girl.Exception;
import girl.girl.enums.ResultEnums;
public class GirlException extends RuntimeException {
private Integer code;
/*构造方法*/
public GirlException(ResultEnums resultEnums) {
super(resultEnums.getMsg());
this.code = resultEnums.getCode();
}
/*get、set方法*/
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
RuntimeException 事务回滚
Exception 没有事物回滚
本博文有两个部分:第一部分是讲的自定义异常类,第二部分讲的自定义枚举类