package com.imooc.exception;
import com.imooc.enums.ResultEnum;
/**
* 这里继承RuntimeException,spring框架对于抛出RuntimeException才会进行事务回滚,不要继承Exception
*/
public class MyException extends RuntimeException{
private Integer code;
public MyException(ResultEnum resultEnum){
super(resultEnum.getMessage());
this.code=resultEnum.getCode();
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
package com.imooc.handler;
import com.imooc.VO.ResultVO;
import com.imooc.exception.MyException;
import com.imooc.utils.ResultVOUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* 统一异常处理
*/
@ControllerAdvice
@Slf4j
public class MyExceptionHandle {
/**
* 这个是捕获所有异常,就是你throw new Exception("你还在上小学吧");,这里就可以进行捕获,将返回值统一为code ,message
* 利用枚举统一管理所有异常code和message
* throw new SellException(ResultEnum.PRODUCT_STOCK_ERROR);
* @param e
* 这个还可以这么写@ExceptionHandler(value = MyException.class)
* @return
*/
@ExceptionHandler(value = Exception.class)
@ResponseBody
public ResultVO handle(Exception e){
if(e instanceof MyException){
MyException myException=(MyException)e;
return ResultVOUtil.error(myException.getCode(),myException.getMessage());
}
log.error("系统异常{}",e);
return ResultVOUtil.error(-1,"未知错误");
}
}
package com.imooc.VO;
import lombok.Data;
/**
* http请求返回的最外层对象
*/
@Data
public class ResultVO<T> {
/** 错误码. */
private Integer code;
/** 提示信息. */
private String msg;
/** 具体内容. */
private T data;
}
package com.imooc.enums;
import lombok.Getter;
/**
* 只需要给getter方法就可以
*/
@Getter
public enum ResultEnum {
PRODUCT_STATUS_ERROR(24, "商品状态不正确"),
LOGIN_FAIL(25, "登录失败, 登录信息不正确"),
LOGOUT_SUCCESS(26, "登出成功"),
;
private Integer code;
private String message;
ResultEnum(Integer code, String message) {
this.code = code;
this.message = message;
}
}
package com.imooc.utils;
import com.imooc.VO.ResultVO;
public class ResultVOUtil {
public static ResultVO success(Object object) {
ResultVO resultVO = new ResultVO();
resultVO.setData(object);
resultVO.setCode(0);
resultVO.setMsg("成功");
return resultVO;
}
public static ResultVO success() {
return success(null);
}
public static ResultVO error(Integer code, String msg) {
ResultVO resultVO = new ResultVO();
resultVO.setCode(code);
resultVO.setMsg(msg);
return resultVO;
}
}