feat: 增加异常check

This commit is contained in:
lilong 2024-03-19 10:32:58 +08:00
parent 6821b3a45a
commit f1925adc85
4 changed files with 692 additions and 0 deletions

View File

@ -0,0 +1,132 @@
package cn.axzo.pokonyan.exception;
import com.google.common.base.Strings;
import java.util.Collection;
import java.util.Objects;
import java.util.function.Supplier;
public abstract class Aassert {
public Aassert() {
}
public static void throwError(ResultCode errorCode) {
throw new BusinessException(errorCode);
}
public static void throwError(ResultCode errorCode, String overrideMessage) {
throw new BusinessException(errorCode.getErrorCode(), overrideMessage);
}
public static void isTrue(boolean expression, ResultCode errorCode) {
if (!expression) {
throw new BusinessException(errorCode);
}
}
public static void isTrue(boolean expression, ResultCode errorCode, String overrideMessage) {
if (!expression) {
throw new BusinessException(errorCode.getErrorCode(), overrideMessage);
}
}
public static void isFalse(boolean expression, ResultCode errorCode) {
isTrue(!expression, errorCode);
}
public static void isFalse(boolean expression, ResultCode errorCode, String overrideMessage) {
isTrue(!expression, errorCode, overrideMessage);
}
public static void isNull(Object object, ResultCode errorCode) {
isTrue(object == null, errorCode);
}
public static void isNull(Object object, ResultCode errorCode, String overrideMessage) {
isTrue(object == null, errorCode, overrideMessage);
}
public static void notNull(Object object, ResultCode errorCode) {
isTrue(object != null, errorCode);
}
public static void notNull(Object object, ResultCode errorCode, String overrideMessage) {
isTrue(object != null, errorCode, overrideMessage);
}
public static void check(boolean expect, String code, String msg) {
if (!expect) {
throw new BusinessException(code, msg);
}
}
public static void check(boolean expect, ResultCode resultCode) {
if (!expect) {
throw resultCode.toException();
}
}
public static void check(boolean expect, ResultCode resultCode, String msg, Object... objects) {
if (!expect) {
throw resultCode.toException(msg, objects);
}
}
public static <T extends Throwable> void check(boolean expect, Supplier<? extends T> supplier) throws Throwable {
if (!expect) {
throw (Throwable)supplier.get();
}
}
public static void checkEquals(Object source, Object target, ResultCode resultCode) {
if (!Objects.equals(source, target)) {
throw resultCode.toException();
}
}
public static void checkEquals(Object source, Object target, ResultCode resultCode, String msg, Object... objects) {
if (!Objects.equals(source, target)) {
throw resultCode.toException(msg, objects);
}
}
public static void checkNonNull(Object target, ResultCode resultCode) {
if (Objects.isNull(target)) {
throw resultCode.toException();
}
}
public static void checkNonNull(Object target, ResultCode resultCode, String msg, Object... objects) {
if (Objects.isNull(target)) {
throw resultCode.toException(msg, objects);
}
}
public static void checkNotEmpty(Collection coll, ResultCode resultCode) {
if (coll == null || coll.isEmpty()) {
throw resultCode.toException();
}
}
public static void checkNotEmpty(Collection coll, ResultCode resultCode, String msg, Object... objects) {
if (coll == null || coll.isEmpty()) {
throw resultCode.toException(msg, objects);
}
}
public static void checkStringNotEmpty(String str, ResultCode resultCode) {
if (Strings.isNullOrEmpty(str)) {
throw resultCode.toException();
}
}
public static void checkStringNotEmpty(String str, ResultCode resultCode, String msg, Object... objects) {
if (Strings.isNullOrEmpty(str)) {
throw resultCode.toException(msg, objects);
}
}
}

View File

@ -0,0 +1,39 @@
package cn.axzo.pokonyan.exception;
public class BusinessException extends RuntimeException {
private static final long serialVersionUID = -4949212560571865637L;
private final String errorCode;
private final String errorMsg;
public BusinessException(ResultCode resultCode) {
super(String.format("BusinessException{errorCode:%s, errorMsg:%s}", resultCode.getErrorCode(), resultCode.getErrorMessage()));
this.errorCode = resultCode.getErrorCode();
this.errorMsg = resultCode.getErrorMessage();
}
public BusinessException(ResultCode resultCode, Throwable cause) {
super(String.format("BusinessException{errorCode:%s, errorMsg:%s}", resultCode.getErrorCode(), resultCode.getErrorMessage()), cause);
this.errorCode = resultCode.getErrorCode();
this.errorMsg = resultCode.getErrorMessage();
}
public BusinessException(String errorCode, String errorMsg) {
super(String.format("BusinessException{errorCode:%s, errorMsg:%s}", errorCode, errorMsg));
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}
public BusinessException(String errorCode, String errorMsg, Throwable cause) {
super(String.format("BusinessException{errorCode:%s, errorMsg:%s}", errorCode, errorMsg), cause);
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}
public String getErrorCode() {
return this.errorCode;
}
public String getErrorMsg() {
return this.errorMsg;
}
}

View File

@ -0,0 +1,35 @@
package cn.axzo.pokonyan.exception;
public interface ResultCode {
Integer DEFAULT_HTTP_ERROR_CODE = 400;
default Integer getHttpCode() {
return DEFAULT_HTTP_ERROR_CODE;
}
String getErrorCode();
String getErrorMessage();
default BusinessException toException() {
return new BusinessException(this);
}
default BusinessException toException(String customMsg) {
return new BusinessException(this.getErrorCode(), customMsg);
}
default BusinessException toException(String customMsg, Object... objects) {
if (objects != null && objects.length != 0) {
String msg = VarParamFormatter.format(customMsg, objects);
if (objects[objects.length - 1] instanceof Throwable) {
Throwable throwable = (Throwable)objects[objects.length - 1];
msg = String.format("%s (%s)", msg, throwable.getClass().getSimpleName());
}
return this.toException(msg);
} else {
return this.toException(customMsg);
}
}
}

View File

@ -0,0 +1,486 @@
package cn.axzo.pokonyan.exception;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class VarParamFormatter {
static final String RECURSION_PREFIX = "[...";
static final String RECURSION_SUFFIX = "...]";
static final String ERROR_PREFIX = "[!!!";
static final String ERROR_SEPARATOR = "=>";
static final String ERROR_MSG_SEPARATOR = ":";
static final String ERROR_SUFFIX = "!!!]";
private static final char DELIM_START = '{';
private static final char DELIM_STOP = '}';
private static final char ESCAPE_CHAR = '\\';
private static ThreadLocal<SimpleDateFormat> threadLocalSimpleDateFormat = new ThreadLocal();
private VarParamFormatter() {
}
static int countArgumentPlaceholders(final String messagePattern) {
if (messagePattern == null) {
return 0;
} else {
int length = messagePattern.length();
int result = 0;
boolean isEscaped = false;
for(int i = 0; i < length - 1; ++i) {
char curChar = messagePattern.charAt(i);
if (curChar == '\\') {
isEscaped = !isEscaped;
} else if (curChar == '{') {
if (!isEscaped && messagePattern.charAt(i + 1) == '}') {
++result;
++i;
}
isEscaped = false;
} else {
isEscaped = false;
}
}
return result;
}
}
static int countArgumentPlaceholders2(final String messagePattern, final int[] indices) {
if (messagePattern == null) {
return 0;
} else {
int length = messagePattern.length();
int result = 0;
boolean isEscaped = false;
for(int i = 0; i < length - 1; ++i) {
char curChar = messagePattern.charAt(i);
if (curChar == '\\') {
isEscaped = !isEscaped;
indices[0] = -1;
++result;
} else if (curChar == '{') {
if (!isEscaped && messagePattern.charAt(i + 1) == '}') {
indices[result] = i;
++result;
++i;
}
isEscaped = false;
} else {
isEscaped = false;
}
}
return result;
}
}
static int countArgumentPlaceholders3(final char[] messagePattern, final int length, final int[] indices) {
int result = 0;
boolean isEscaped = false;
for(int i = 0; i < length - 1; ++i) {
char curChar = messagePattern[i];
if (curChar == '\\') {
isEscaped = !isEscaped;
} else if (curChar == '{') {
if (!isEscaped && messagePattern[i + 1] == '}') {
indices[result] = i;
++result;
++i;
}
isEscaped = false;
} else {
isEscaped = false;
}
}
return result;
}
public static String format(final String messagePattern, final Object[] arguments) {
StringBuilder result = new StringBuilder();
int argCount = arguments == null ? 0 : arguments.length;
formatMessage(result, messagePattern, arguments, argCount);
return result.toString();
}
static void formatMessage2(final StringBuilder buffer, final String messagePattern, final Object[] arguments, final int argCount, final int[] indices) {
if (messagePattern != null && arguments != null && argCount != 0) {
int previous = 0;
for(int i = 0; i < argCount; ++i) {
buffer.append(messagePattern, previous, indices[i]);
previous = indices[i] + 2;
recursiveDeepToString(arguments[i], buffer, (Set)null);
}
buffer.append(messagePattern, previous, messagePattern.length());
} else {
buffer.append(messagePattern);
}
}
static void formatMessage3(final StringBuilder buffer, final char[] messagePattern, final int patternLength, final Object[] arguments, final int argCount, final int[] indices) {
if (messagePattern != null) {
if (arguments != null && argCount != 0) {
int previous = 0;
for(int i = 0; i < argCount; ++i) {
buffer.append(messagePattern, previous, indices[i]);
previous = indices[i] + 2;
recursiveDeepToString(arguments[i], buffer, (Set)null);
}
buffer.append(messagePattern, previous, patternLength);
} else {
buffer.append(messagePattern);
}
}
}
static void formatMessage(final StringBuilder buffer, final String messagePattern, final Object[] arguments, final int argCount) {
if (messagePattern != null && arguments != null && argCount != 0) {
int escapeCounter = 0;
int currentArgument = 0;
int i = 0;
int len;
for(len = messagePattern.length(); i < len - 1; ++i) {
char curChar = messagePattern.charAt(i);
if (curChar == '\\') {
++escapeCounter;
} else {
if (isDelimPair(curChar, messagePattern, i)) {
++i;
writeEscapedEscapeChars(escapeCounter, buffer);
if (isOdd(escapeCounter)) {
writeDelimPair(buffer);
} else {
writeArgOrDelimPair(arguments, argCount, currentArgument, buffer);
++currentArgument;
}
} else {
handleLiteralChar(buffer, escapeCounter, curChar);
}
escapeCounter = 0;
}
}
handleRemainingCharIfAny(messagePattern, len, buffer, escapeCounter, i);
} else {
buffer.append(messagePattern);
}
}
private static boolean isDelimPair(final char curChar, final String messagePattern, final int curCharIndex) {
return curChar == '{' && messagePattern.charAt(curCharIndex + 1) == '}';
}
private static void handleRemainingCharIfAny(final String messagePattern, final int len, final StringBuilder buffer, final int escapeCounter, final int i) {
if (i == len - 1) {
char curChar = messagePattern.charAt(i);
handleLastChar(buffer, escapeCounter, curChar);
}
}
private static void handleLastChar(final StringBuilder buffer, final int escapeCounter, final char curChar) {
if (curChar == '\\') {
writeUnescapedEscapeChars(escapeCounter + 1, buffer);
} else {
handleLiteralChar(buffer, escapeCounter, curChar);
}
}
private static void handleLiteralChar(final StringBuilder buffer, final int escapeCounter, final char curChar) {
writeUnescapedEscapeChars(escapeCounter, buffer);
buffer.append(curChar);
}
private static void writeDelimPair(final StringBuilder buffer) {
buffer.append('{');
buffer.append('}');
}
private static boolean isOdd(final int number) {
return (number & 1) == 1;
}
private static void writeEscapedEscapeChars(final int escapeCounter, final StringBuilder buffer) {
int escapedEscapes = escapeCounter >> 1;
writeUnescapedEscapeChars(escapedEscapes, buffer);
}
private static void writeUnescapedEscapeChars(int escapeCounter, final StringBuilder buffer) {
while(escapeCounter > 0) {
buffer.append('\\');
--escapeCounter;
}
}
private static void writeArgOrDelimPair(final Object[] arguments, final int argCount, final int currentArgument, final StringBuilder buffer) {
if (currentArgument < argCount) {
recursiveDeepToString(arguments[currentArgument], buffer, (Set)null);
} else {
writeDelimPair(buffer);
}
}
static String deepToString(final Object o) {
if (o == null) {
return null;
} else if (o instanceof String) {
return (String)o;
} else {
StringBuilder str = new StringBuilder();
Set<String> dejaVu = new HashSet();
recursiveDeepToString(o, str, dejaVu);
return str.toString();
}
}
private static void recursiveDeepToString(final Object o, final StringBuilder str, final Set<String> dejaVu) {
if (!appendSpecialTypes(o, str)) {
if (isMaybeRecursive(o)) {
appendPotentiallyRecursiveValue(o, str, dejaVu);
} else {
tryObjectToString(o, str);
}
}
}
private static boolean appendSpecialTypes(final Object o, final StringBuilder str) {
if (o != null && !(o instanceof String)) {
if (o instanceof CharSequence) {
str.append((CharSequence)o);
return true;
} else if (o instanceof Integer) {
str.append((Integer)o);
return true;
} else if (o instanceof Long) {
str.append((Long)o);
return true;
} else if (o instanceof Double) {
str.append((Double)o);
return true;
} else if (o instanceof Boolean) {
str.append((Boolean)o);
return true;
} else if (o instanceof Character) {
str.append((Character)o);
return true;
} else if (o instanceof Short) {
str.append((Short)o);
return true;
} else if (o instanceof Float) {
str.append((Float)o);
return true;
} else {
return appendDate(o, str);
}
} else {
str.append((String)o);
return true;
}
}
private static boolean appendDate(final Object o, final StringBuilder str) {
if (!(o instanceof Date)) {
return false;
} else {
Date date = (Date)o;
SimpleDateFormat format = getSimpleDateFormat();
str.append(format.format(date));
return true;
}
}
private static SimpleDateFormat getSimpleDateFormat() {
SimpleDateFormat result = (SimpleDateFormat)threadLocalSimpleDateFormat.get();
if (result == null) {
result = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
threadLocalSimpleDateFormat.set(result);
}
return result;
}
private static boolean isMaybeRecursive(final Object o) {
return o.getClass().isArray() || o instanceof Map || o instanceof Collection;
}
private static void appendPotentiallyRecursiveValue(final Object o, final StringBuilder str, final Set<String> dejaVu) {
Class<?> oClass = o.getClass();
if (oClass.isArray()) {
appendArray(o, str, dejaVu, oClass);
} else if (o instanceof Map) {
appendMap(o, str, dejaVu);
} else if (o instanceof Collection) {
appendCollection(o, str, dejaVu);
}
}
private static void appendArray(final Object o, final StringBuilder str, Set<String> dejaVu, final Class<?> oClass) {
if (oClass == byte[].class) {
str.append(Arrays.toString((byte[])o));
} else if (oClass == short[].class) {
str.append(Arrays.toString((short[])o));
} else if (oClass == int[].class) {
str.append(Arrays.toString((int[])o));
} else if (oClass == long[].class) {
str.append(Arrays.toString((long[])o));
} else if (oClass == float[].class) {
str.append(Arrays.toString((float[])o));
} else if (oClass == double[].class) {
str.append(Arrays.toString((double[])o));
} else if (oClass == boolean[].class) {
str.append(Arrays.toString((boolean[])o));
} else if (oClass == char[].class) {
str.append(Arrays.toString((char[])o));
} else {
if (dejaVu == null) {
dejaVu = new HashSet();
}
String id = identityToString(o);
if (((Set)dejaVu).contains(id)) {
str.append("[...").append(id).append("...]");
} else {
((Set)dejaVu).add(id);
Object[] oArray = (Object[])o;
str.append('[');
boolean first = true;
Object[] var7 = oArray;
int var8 = oArray.length;
for(int var9 = 0; var9 < var8; ++var9) {
Object current = var7[var9];
if (first) {
first = false;
} else {
str.append(", ");
}
recursiveDeepToString(current, str, new HashSet((Collection)dejaVu));
}
str.append(']');
}
}
}
private static void appendMap(final Object o, final StringBuilder str, Set<String> dejaVu) {
if (dejaVu == null) {
dejaVu = new HashSet();
}
String id = identityToString(o);
if (((Set)dejaVu).contains(id)) {
str.append("[...").append(id).append("...]");
} else {
((Set)dejaVu).add(id);
Map<?, ?> oMap = (Map)o;
str.append('{');
boolean isFirst = true;
Iterator var6 = oMap.entrySet().iterator();
while(var6.hasNext()) {
Object o1 = var6.next();
Map.Entry<?, ?> current = (Map.Entry)o1;
if (isFirst) {
isFirst = false;
} else {
str.append(", ");
}
Object key = current.getKey();
Object value = current.getValue();
recursiveDeepToString(key, str, new HashSet((Collection)dejaVu));
str.append('=');
recursiveDeepToString(value, str, new HashSet((Collection)dejaVu));
}
str.append('}');
}
}
private static void appendCollection(final Object o, final StringBuilder str, Set<String> dejaVu) {
if (dejaVu == null) {
dejaVu = new HashSet();
}
String id = identityToString(o);
if (((Set)dejaVu).contains(id)) {
str.append("[...").append(id).append("...]");
} else {
((Set)dejaVu).add(id);
Collection<?> oCol = (Collection)o;
str.append('[');
boolean isFirst = true;
Object anOCol;
for(Iterator var6 = oCol.iterator(); var6.hasNext(); recursiveDeepToString(anOCol, str, new HashSet((Collection)dejaVu))) {
anOCol = var6.next();
if (isFirst) {
isFirst = false;
} else {
str.append(", ");
}
}
str.append(']');
}
}
private static void tryObjectToString(final Object o, final StringBuilder str) {
try {
str.append(o.toString());
} catch (Throwable var3) {
handleErrorInObjectToString(o, str, var3);
}
}
private static void handleErrorInObjectToString(final Object o, final StringBuilder str, final Throwable t) {
str.append("[!!!");
str.append(identityToString(o));
str.append("=>");
String msg = t.getMessage();
String className = t.getClass().getName();
str.append(className);
if (!className.equals(msg)) {
str.append(":");
str.append(msg);
}
str.append("!!!]");
}
static String identityToString(final Object obj) {
if (obj == null) {
return null;
} else {
String var10000 = obj.getClass().getName();
return var10000 + "@" + Integer.toHexString(System.identityHashCode(obj));
}
}
}