报错内容 ExceptionMsg
package com.io.common.enums;
public enum ExceptionMsg {
SUCCESS_CODE(0,"成功"),
SYS_REQUEST_ERROR(-1,"系统出现错误, 请联系网站管理员 !"),
TOEKN_INVALID(010000,"invalid token header"),
TOKEN_EXPIRED(010001,"token过期,请重新登录"),
TOKEN_VERIFY_ERROR(010002,"Token验证异常"),
TOKEN_IS_NULL(010003,"token不能为空"),
;
private Integer code;
private String msg;
ExceptionMsg(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public Integer getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
报错调用类 SystemException
package com.io.common.exception;
import com.io.common.enums.ExceptionMsg;
import org.apache.commons.lang3.StringUtils;
public class SystemException {
public static void myException(ExceptionMsg msg) {
throw new MyException(msg.getCode(), msg.getMsg());
}
public static void myException(ExceptionMsg msg, Object... args) {
String message = msg.getMsg();
if(args.length > 0) {
if(StringUtils.isBlank(message)) {
message = msg.getMsg();
}
message = String.format(message, args);
}
throw new MyException(msg.getCode(), message);
}
}
调用类二 MyException
package com.io.common.exception;
import java.io.Serializable;
public class MyException extends RuntimeException implements Serializable {
private static final long serialVersionUID = 1L;
private Integer code;
public MyException() {
}
public MyException(Integer code, String message) {
super(message);
this.code = code;
}
public MyException(Integer code, String message, Throwable cause) {
super(message, cause);
this.code = code;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
最终实现类
package com.io.exception;
import com.io.common.exception.MyException;
import com.io.util.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class RRExceptionHandler {
private Logger logger = LoggerFactory.getLogger(getClass());
@ExceptionHandler(MyException.class)
public R handleRRException(MyException e) {
R r = new R();
r.put("code", e.getCode());
r.put("msg", e.getMessage());
return r;
}
@ExceptionHandler(DuplicateKeyException.class)
public R handleDuplicateKeyException(DuplicateKeyException e) {
logger.error(e.getMessage(), e);
return R.error("数据库中已存在该记录");
}
@ExceptionHandler(Exception.class)
public R handleException(Exception e) {
logger.error(e.getMessage(), e);
return R.error(e.getMessage());
}
}
使用
SystemException.myException(ExceptionMsg.TOKEN_IS_NULL);