shz.core.msg.FailureMsg Maven / Gradle / Ivy
package shz.core.msg;
import shz.core.NullHelp;
import shz.core.PRException;
import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.TimeoutException;
public interface FailureMsg extends Message {
@Override
default boolean isOk() {
return false;
}
static FailureMsg fail(int code, String msg) {
switch (code) {
case 400:
return ClientFailureMsg.fail(msg);
case 500:
return ServerFailureMsg.fail(msg);
default:
return new FailureMsg() {
private static final long serialVersionUID = 1961453901730505807L;
@Override
public int code() {
return code;
}
@Override
public String msg() {
return msg;
}
};
}
}
static FailureMsg fail(Throwable cause, boolean stackTrace) {
if (cause == null) return ServerFailure.INTERNAL_ERROR;
if (cause instanceof InvocationTargetException)
cause = ((InvocationTargetException) cause).getTargetException();
if (cause instanceof PRException) return ((PRException) cause).msg();
if (cause instanceof TimeoutException) return ServerFailure.GATEWAY_TIMEOUT;
if (cause instanceof SecurityException) return ClientFailure.FORBIDDEN;
String message = cause.getLocalizedMessage();
if (stackTrace && NullHelp.isBlank(message)) return ServerFailureMsg.fail(PRException.stackTrace(cause));
return ServerFailureMsg.fail(message);
}
static FailureMsg fail(Throwable cause) {
return fail(cause, true);
}
default void requireNon(boolean condition) {
if (condition) throw PRException.of(this);
}
default T requireNonNull(T obj) {
if (obj == null) throw PRException.of(this);
return obj;
}
default T requireNonAnyNull(T obj) {
if (NullHelp.isAnyNull(obj)) throw PRException.of(this);
return obj;
}
default T requireNonEmpty(T obj) {
if (NullHelp.isEmpty(obj)) throw PRException.of(this);
return obj;
}
default T requireNonAnyEmpty(T obj) {
if (NullHelp.isAnyEmpty(obj)) throw PRException.of(this);
return obj;
}
default T requireNonBlank(T obj) {
if (NullHelp.isBlank(obj)) throw PRException.of(this);
return obj;
}
default T requireNonAnyBlank(T obj) {
if (NullHelp.isAnyBlank(obj)) throw PRException.of(this);
return obj;
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy