Spring boot统一异常处理
- 统一异常处理通常是结核Result使用
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;
}
}
当然也要封装一个静态的ResultUtil
public class ResultUtil {
public static Result success(Object object){
Result result = new Result();
result.setCode(0);
result.setMsg("成功");
result.setData(object);
return result;
}
public static Result success(){
return success(null);
}
public static Result error(Integer code,String msg){
Result result = new Result();
result.setCode(code);
result.setMsg(msg);
return result;
}
}
2.定义全局枚举异常变量
在这里插入代码片
3.自定义Exception
/** 自定义异常 对象
* @Author: Mr xyushao
* @Date: 2020/3/17 0017 15:22
*/
public class LuckyException extends RuntimeException {
private Integer code;
public LuckyException(ResultEnums resultEnums){
super(resultEnums.getMessage());
setCode(resultEnums.getCode());
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
3.自定义捕获异常处理
/** 捕获异常并处理
* @Author: Mr xyushao
* @Date: 2020/3/16 0016 18:41
*/
@ControllerAdvice
public class ExceptionHandle {
@ExceptionHandler(value = Exception.class) //声明捕获哪个异常类
@ResponseBody
public Result handler(Exception e){
if (e instanceof LuckyException){ //判断异常是否为我们定义的LuckyException
LuckyException luckyException = (LuckyException) e;
return ResultUtil.error(luckyException.getCode(),luckyException.getMessage());
}else{
return ResultUtil.error(-1,"未知异常");
}
}
}
- 在service层作业务处理,所以异常通常是在service层进行抛出异常
public LuckyMoney getMoney(Integer id) {
LuckyMoney luckyMoney = repository.findById(id).orElse(null);
BigDecimal money = luckyMoney.getMoney();
if (money.intValue()<=0){
//小于0
throw new LuckyException(ResultEnums.MIN_MONEY);
}else{
return luckyMoney;
}
}