public interface BaseExceptionInterface {
Integer getCode();
String getMessage();
}
- 然后基于此接口扩展不同的业务异常枚举类,这里给一个万能的用户异常枚举类demo
public enum UserExceptionEnum implements BaseExceptionInterface {
USER_NOT_EXIST_ERROR(10000, "用户不存在"),
;
private final Integer code;
private final String message;
UserExceptionEnum(Integer code, String message) {
this.code = code;
this.message = message;
}
@Override
public Integer getCode() {
return code;
}
@Override
public String getMessage() {
return message;
}
}
public class CommonException extends RuntimeException {
private final Integer errorCode;
private final String errorMessage;
public CommonException(Integer errorCode, String errorMessage) {
super();
this.errorCode = errorCode;
this.errorMessage = errorMessage;
}
public CommonException(BaseExceptionInterface baseExceptionInterface) {
super(baseExceptionInterface.getMessage());
this.errorCode = baseExceptionInterface.getCode();
this.errorMessage = baseExceptionInterface.getMessage();
}
public CommonException(BaseExceptionInterface baseExceptionInterface, Object... params) {
this(baseExceptionInterface.getCode(), MessageFormat.format(baseExceptionInterface.getMessage(), params));
}
public CommonException(BaseExceptionInterface baseExceptionInterface, Throwable throwable) {
super(baseExceptionInterface.getMessage(), throwable);
this.errorCode = baseExceptionInterface.getCode();
this.errorMessage = baseExceptionInterface.getMessage();
}
public Integer getErrorCode() {
return errorCode;
}
public String getErrorMessage() {
return errorMessage;
}
}
throw new CommonException(UserExceptionEnum.USER_NOT_EXIST_ERROR);
- 扩展业务异常时也只需要扩展对应的异常枚举类信息即可