定义异常枚举
package com.imooc.enums;
/**
* 定义异常枚举
* Created by Administrator on 2018/12/1.
*/
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;
}
}
自定义异常
package com.imooc.exception;
import com.imooc.enums.ResultEnum;
/**
* 自定义异常
* Created by Administrator on 2018/12/1.
*/
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;
}
}
异常捕获
package com.imooc.handle;
import com.imooc.domain.Result;
import com.imooc.exception.GirlException;
import com.imooc.utils.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* 异常捕获
* Created by Administrator on 2018/12/1.
*/
@ControllerAdvice
public class ExceptionHandle {
//打印系统日志使用
private final static Logger logger= LoggerFactory.getLogger(ExceptionHandle.class);
@ExceptionHandler(value = Exception.class)
@ResponseBody
public Result handle(Exception e) {
if (e instanceof GirlException) {
GirlException girlException = (GirlException) e;
return ResultUtil.error(girlException.getCode(), girlException.getMessage());
} else {
logger.error("【系统异常】{}",e);
return ResultUtil.error(-1, "未知错误");
}
}
}
Service中调用方法
public void getAge(Integer id) throws Exception {
Girl girl=girlRepository.findOne(id);
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);
}
}