一、UserException.java
import lombok.Getter;
/**
* @author :cw
* @date :Created in 2020/8/6 上午9:31
* @description:自定义用户异常
* @modified By:
* @version: $
*/
@Getter
public class UserException extends RuntimeException{
private Integer code;
public UserException(Integer code, String msg){
super(msg);
this.code = code;
}
public UserException(ResultCode resultCode) {
super(resultCode.getMessage());
this.code = resultCode.getCode();
}
}
其中ResultCode为封装的枚举类,具体根据情况。
二、AdminException.java
import lombok.Getter;
/**
* @author :cw
* @date :Created in 2020/8/10 下午4:47
* @description:
* @modified By:
* @version: $
*/
@Getter
public class AdminException extends RuntimeException{
private Integer code;
public AdminException(Integer code, String msg){
super(msg);
this.code = code;
}
public AdminException(ResultCode resultCode) {
super(resultCode.getMessage());
this.code = resultCode.getCode();
}
}
三、GlobalException.java
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;
/**
* @author :cw
* @date :Created in 2020/8/6 上午9:30
* @description:全剧异常处理
* @modified By:
* @version: $
*/
@ControllerAdvice
@Slf4j
public class GlobalException {
@ExceptionHandler(value = Exception.class)
@ResponseBody
public Result exception(Exception e) {
log.error("系统繁忙: {}", e.getMessage());
return ResultUtil.FAILED(e.getMessage());
}
@ExceptionHandler(value = UserException.class)
@ResponseBody
public Result userException(UserException e) {
return ResultUtil.CustomResultParam(false,e.getCode(), e.getMessage());
}
@ExceptionHandler(value = AdminException.class)
@ResponseBody
public Result adminException(AdminException e) {
return ResultUtil.CustomResultParam(false,e.getCode(), e.getMessage());
}
}
其中ResultUtil.FAILED、ResultUtil.CustomResultParam(false,e.getCode(), e.getMessage());为封装的统计返回结果,具体根据情况。
四、使用方法
例如:
public Student insertPhoneLoginInfos(Student stuDto) {
try {
userMapper.inserStuInfos(stuDto);
// 有的话获取信息
return stuDto;
} catch (Exception e) {
throw new UserException(ResultCode.USER_PHONE_LOGIN_INSERT_LOCAL_ERROR);
}
}