优化:优化校验工具类的使用及部分模板文本写法

1.优化校验工具类,支持传入 {} 模板文本
2.校验工具类增加 throwIf 重载方法,适合于 boolean 类型参数的情况
3.优化一些模板文本的写法
4.优化一些其他细节
This commit is contained in:
Charles7c 2023-03-20 20:44:52 +08:00
parent 139cb337d7
commit 6d3ba478e9
13 changed files with 265 additions and 177 deletions

View File

@ -16,10 +16,7 @@
package top.charles7c.cnadmin.common.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.*;
/**
* 查询注解
@ -29,6 +26,7 @@ import java.lang.annotation.Target;
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Query {
/**

View File

@ -208,7 +208,7 @@ public abstract class BaseServiceImpl<M extends BaseMapper<T>, T extends BaseDO,
*/
protected T getById(Object id) {
T entity = baseMapper.selectById(Convert.toStr(id));
CheckUtils.throwIfNull(entity, ClassUtil.getClassName(entityClass, true), "ID", id);
CheckUtils.throwIfNotExists(entity, ClassUtil.getClassName(entityClass, true), "ID", id);
return entity;
}

View File

@ -64,7 +64,7 @@ public class GlobalExceptionHandler {
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(Exception.class)
public R handleException(Exception e, HttpServletRequest request) {
log.error("请求地址'{}',发生未知异常", request.getRequestURI(), e);
log.error("请求地址 [{}],发生未知异常。", request.getRequestURI(), e);
LogContextHolder.setException(e);
return R.fail(e.getMessage());
}
@ -75,7 +75,7 @@ public class GlobalExceptionHandler {
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(RuntimeException.class)
public R handleRuntimeException(RuntimeException e, HttpServletRequest request) {
log.error("请求地址'{}',发生系统异常", request.getRequestURI(), e);
log.error("请求地址 [{}],发生系统异常。", request.getRequestURI(), e);
LogContextHolder.setException(e);
return R.fail(e.getMessage());
}
@ -86,7 +86,7 @@ public class GlobalExceptionHandler {
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(ServiceException.class)
public R handleServiceException(ServiceException e, HttpServletRequest request) {
log.error("请求地址'{}',发生业务异常", request.getRequestURI(), e);
log.error("请求地址 [{}],发生业务异常。", request.getRequestURI(), e);
LogContextHolder.setErrorMsg(e.getMessage());
return R.fail(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage());
}
@ -97,7 +97,7 @@ public class GlobalExceptionHandler {
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(BadRequestException.class)
public R handleBadRequestException(BadRequestException e, HttpServletRequest request) {
log.warn("请求地址'{}',自定义验证失败", request.getRequestURI(), e);
log.warn("请求地址 [{}],自定义验证失败。", request.getRequestURI(), e);
LogContextHolder.setErrorMsg(e.getMessage());
return R.fail(HttpStatus.BAD_REQUEST.value(), e.getMessage());
}
@ -108,7 +108,7 @@ public class GlobalExceptionHandler {
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(BindException.class)
public R handleBindException(BindException e, HttpServletRequest request) {
log.warn("请求地址'{}',参数验证失败", request.getRequestURI(), e);
log.warn("请求地址 [{}],参数验证失败。", request.getRequestURI(), e);
String errorMsg = StreamUtils.join(e.getAllErrors(), DefaultMessageSourceResolvable::getDefaultMessage, "");
LogContextHolder.setErrorMsg(errorMsg);
return R.fail(HttpStatus.BAD_REQUEST.value(), errorMsg);
@ -120,7 +120,7 @@ public class GlobalExceptionHandler {
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(ConstraintViolationException.class)
public R constraintViolationException(ConstraintViolationException e, HttpServletRequest request) {
log.warn("请求地址'{}',参数验证失败", request.getRequestURI(), e);
log.warn("请求地址 [{}],参数验证失败。", request.getRequestURI(), e);
String errorMsg = StreamUtils.join(e.getConstraintViolations(), ConstraintViolation::getMessage, "");
LogContextHolder.setErrorMsg(errorMsg);
return R.fail(HttpStatus.BAD_REQUEST.value(), errorMsg);
@ -132,7 +132,7 @@ public class GlobalExceptionHandler {
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public R handleMethodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request) {
log.warn("请求地址'{}',参数验证失败", request.getRequestURI(), e);
log.warn("请求地址 [{}],参数验证失败。", request.getRequestURI(), e);
String errorMsg = ExceptionUtils
.exToNull(() -> Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage());
LogContextHolder.setErrorMsg(errorMsg);
@ -146,11 +146,10 @@ public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
public R handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e,
HttpServletRequest request) {
String subMsg = StrUtil.format("参数名:'{}',期望参数类型:'{}'", e.getName(), e.getParameter().getParameterType());
log.warn("请求地址'{}',参数转换失败。方法:'{}'{}", request.getRequestURI(),
Objects.requireNonNull(e.getParameter().getMethod()).getName(), subMsg, e);
LogContextHolder.setErrorMsg(subMsg);
return R.fail(HttpStatus.BAD_REQUEST.value(), subMsg);
String errorMsg = StrUtil.format("参数名:[{}],期望参数类型:[{}]", e.getName(), e.getParameter().getParameterType());
log.warn("请求地址 [{}],参数转换失败,{}。", request.getRequestURI(), errorMsg, e);
LogContextHolder.setErrorMsg(errorMsg);
return R.fail(HttpStatus.BAD_REQUEST.value(), errorMsg);
}
/**
@ -160,7 +159,7 @@ public class GlobalExceptionHandler {
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public R handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e, HttpServletRequest request) {
LogContextHolder.setErrorMsg(e.getMessage());
log.error("请求地址'{}',不支持'{}'请求", request.getRequestURI(), e.getMethod());
log.error("请求地址 [{}],不支持 [{}] 请求", request.getRequestURI(), e.getMethod());
return R.fail(HttpStatus.METHOD_NOT_ALLOWED.value(), e.getMessage());
}
@ -170,9 +169,9 @@ public class GlobalExceptionHandler {
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MaxUploadSizeExceededException.class)
public R handleMaxUploadSizeExceededException(MaxUploadSizeExceededException e, HttpServletRequest request) {
log.warn("请求地址'{}',上传文件失败,文件大小超过限制", request.getRequestURI(), e);
log.warn("请求地址 [{}],上传文件失败,文件大小超过限制。", request.getRequestURI(), e);
String sizeLimit = StrUtil.subBetween(e.getMessage(), "The maximum size ", " for");
String errorMsg = String.format("请上传小于 %s MB 的文件", NumberUtil.parseLong(sizeLimit) / 1024 / 1024);
String errorMsg = String.format("请上传小于 %sMB 的文件", NumberUtil.parseLong(sizeLimit) / 1024 / 1024);
LogContextHolder.setErrorMsg(errorMsg);
return R.fail(HttpStatus.BAD_REQUEST.value(), errorMsg);
}
@ -183,7 +182,7 @@ public class GlobalExceptionHandler {
@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ExceptionHandler(NotLoginException.class)
public R handleNotLoginException(NotLoginException e, HttpServletRequest request) {
log.error("请求地址'{}',认证失败,无法访问系统资源", request.getRequestURI(), e);
log.error("请求地址 [{}],认证失败,无法访问系统资源。", request.getRequestURI(), e);
String errorMsg;
switch (e.getType()) {
@ -208,7 +207,7 @@ public class GlobalExceptionHandler {
@ResponseStatus(HttpStatus.FORBIDDEN)
@ExceptionHandler(NotPermissionException.class)
public R handleNotPermissionException(NotPermissionException e, HttpServletRequest request) {
log.error("请求地址'{}',权限码校验失败'{}'", request.getRequestURI(), e);
log.error("请求地址 [{}],权限码校验失败。", request.getRequestURI(), e);
return R.fail(HttpStatus.FORBIDDEN.value(), "没有访问权限,请联系管理员授权");
}
@ -218,7 +217,7 @@ public class GlobalExceptionHandler {
@ResponseStatus(HttpStatus.FORBIDDEN)
@ExceptionHandler(NotRoleException.class)
public R handleNotRoleException(NotRoleException e, HttpServletRequest request) {
log.error("请求地址'{}',角色权限校验失败'{}'", request.getRequestURI(), e);
log.error("请求地址 [{}],角色权限校验失败。", request.getRequestURI(), e);
return R.fail(HttpStatus.FORBIDDEN.value(), "没有访问权限,请联系管理员授权");
}
}

View File

@ -40,19 +40,7 @@ public class CheckUtils extends Validator {
private static final Class<ServiceException> EXCEPTION_TYPE = ServiceException.class;
/**
* 如果为空抛出异常
*
* @param obj
* 被检测的对象
* @param message
* 错误信息
*/
public static void throwIfNull(Object obj, String message) {
throwIfNull(obj, message, EXCEPTION_TYPE);
}
/**
* 如果为空抛出异常
* 如果不存在抛出异常
*
* @param obj
* 被检测的对象
@ -63,22 +51,38 @@ public class CheckUtils extends Validator {
* @param fieldValue
* 字段值
*/
public static void throwIfNull(Object obj, String entityName, String fieldName, Object fieldValue) {
public static void throwIfNotExists(Object obj, String entityName, String fieldName, Object fieldValue) {
String message =
String.format("%s 为 [%s] 的 %s 记录已不存在", fieldName, fieldValue, StrUtil.replace(entityName, "DO", ""));
throwIfNull(obj, message, EXCEPTION_TYPE);
}
/**
* 如果为空抛出异常
*
* @param obj
* 被检测的对象
* @param template
* 异常信息模板被替换的部分用 {} 表示如果模板为 null返回 "null"
* @param params
* 参数值
*/
public static void throwIfNull(Object obj, String template, Object... params) {
throwIfNull(obj, StrUtil.format(template, params), EXCEPTION_TYPE);
}
/**
* 如果不为空抛出异常
*
* @param obj
* 被检测的对象
* @param message
* 错误信息
* @param template
* 异常信息模板被替换的部分用 {} 表示如果模板为 null返回 "null"
* @param params
* 参数值
*/
public static void throwIfNotNull(Object obj, String message) {
throwIfNotNull(obj, message, EXCEPTION_TYPE);
public static void throwIfNotNull(Object obj, String template, Object... params) {
throwIfNotNull(obj, StrUtil.format(template, params), EXCEPTION_TYPE);
}
/**
@ -103,11 +107,13 @@ public class CheckUtils extends Validator {
*
* @param obj
* 被检测的对象
* @param message
* 错误信息
* @param template
* 异常信息模板被替换的部分用 {} 表示如果模板为 null返回 "null"
* @param params
* 参数值
*/
public static void throwIfEmpty(Object obj, String message) {
throwIfEmpty(obj, message, EXCEPTION_TYPE);
public static void throwIfEmpty(Object obj, String template, Object... params) {
throwIfEmpty(obj, StrUtil.format(template, params), EXCEPTION_TYPE);
}
/**
@ -115,11 +121,13 @@ public class CheckUtils extends Validator {
*
* @param obj
* 被检测的对象
* @param message
* 错误信息
* @param template
* 异常信息模板被替换的部分用 {} 表示如果模板为 null返回 "null"
* @param params
* 参数值
*/
public static void throwIfNotEmpty(Object obj, String message) {
throwIfNotEmpty(obj, message, EXCEPTION_TYPE);
public static void throwIfNotEmpty(Object obj, String template, Object... params) {
throwIfNotEmpty(obj, StrUtil.format(template, params), EXCEPTION_TYPE);
}
/**
@ -127,11 +135,13 @@ public class CheckUtils extends Validator {
*
* @param str
* 被检测的字符串
* @param message
* 错误信息
* @param template
* 异常信息模板被替换的部分用 {} 表示如果模板为 null返回 "null"
* @param params
* 参数值
*/
public static void throwIfBlank(CharSequence str, String message) {
throwIfBlank(str, message, EXCEPTION_TYPE);
public static void throwIfBlank(CharSequence str, String template, Object... params) {
throwIfBlank(str, StrUtil.format(template, params), EXCEPTION_TYPE);
}
/**
@ -139,11 +149,13 @@ public class CheckUtils extends Validator {
*
* @param str
* 被检测的字符串
* @param message
* 错误信息
* @param template
* 异常信息模板被替换的部分用 {} 表示如果模板为 null返回 "null"
* @param params
* 参数值
*/
public static void throwIfNotBlank(CharSequence str, String message) {
throwIfNotBlank(str, message, EXCEPTION_TYPE);
public static void throwIfNotBlank(CharSequence str, String template, Object... params) {
throwIfNotBlank(str, StrUtil.format(template, params), EXCEPTION_TYPE);
}
/**
@ -153,11 +165,13 @@ public class CheckUtils extends Validator {
* 要比较的对象1
* @param obj2
* 要比较的对象2
* @param message
* 错误信息
* @param template
* 异常信息模板被替换的部分用 {} 表示如果模板为 null返回 "null"
* @param params
* 参数值
*/
public static void throwIfEqual(Object obj1, Object obj2, String message) {
throwIfEqual(obj1, obj2, message, EXCEPTION_TYPE);
public static void throwIfEqual(Object obj1, Object obj2, String template, Object... params) {
throwIfEqual(obj1, obj2, StrUtil.format(template, params), EXCEPTION_TYPE);
}
/**
@ -167,11 +181,13 @@ public class CheckUtils extends Validator {
* 要比较的对象1
* @param obj2
* 要比较的对象2
* @param message
* 错误信息
* @param template
* 异常信息模板被替换的部分用 {} 表示如果模板为 null返回 "null"
* @param params
* 参数值
*/
public static void throwIfNotEqual(Object obj1, Object obj2, String message) {
throwIfNotEqual(obj1, obj2, message, EXCEPTION_TYPE);
public static void throwIfNotEqual(Object obj1, Object obj2, String template, Object... params) {
throwIfNotEqual(obj1, obj2, StrUtil.format(template, params), EXCEPTION_TYPE);
}
/**
@ -181,11 +197,13 @@ public class CheckUtils extends Validator {
* 要比较的字符串1
* @param str2
* 要比较的字符串2
* @param message
* 错误信息
* @param template
* 异常信息模板被替换的部分用 {} 表示如果模板为 null返回 "null"
* @param params
* 参数值
*/
public static void throwIfEqualIgnoreCase(CharSequence str1, CharSequence str2, String message) {
throwIfEqualIgnoreCase(str1, str2, message, EXCEPTION_TYPE);
public static void throwIfEqualIgnoreCase(CharSequence str1, CharSequence str2, String template, Object... params) {
throwIfEqualIgnoreCase(str1, str2, StrUtil.format(template, params), EXCEPTION_TYPE);
}
/**
@ -195,11 +213,28 @@ public class CheckUtils extends Validator {
* 要比较的字符串1
* @param str2
* 要比较的字符串2
* @param message
* 错误信息
* @param template
* 异常信息模板被替换的部分用 {} 表示如果模板为 null返回 "null"
* @param params
* 参数值
*/
public static void throwIfNotEqualIgnoreCase(CharSequence str1, CharSequence str2, String message) {
throwIfNotEqualIgnoreCase(str1, str2, message, EXCEPTION_TYPE);
public static void throwIfNotEqualIgnoreCase(CharSequence str1, CharSequence str2, String template,
Object... params) {
throwIfNotEqualIgnoreCase(str1, str2, StrUtil.format(template, params), EXCEPTION_TYPE);
}
/**
* 如果条件成立抛出异常
*
* @param condition
* 条件
* @param template
* 异常信息模板被替换的部分用 {} 表示如果模板为 null返回 "null"
* @param params
* 参数值
*/
public static void throwIf(boolean condition, String template, Object... params) {
throwIf(condition, StrUtil.format(template, params), EXCEPTION_TYPE);
}
/**
@ -207,10 +242,12 @@ public class CheckUtils extends Validator {
*
* @param conditionSupplier
* 条件
* @param message
* 错误信息
* @param template
* 异常信息模板被替换的部分用 {} 表示如果模板为 null返回 "null"
* @param params
* 参数值
*/
public static void throwIf(BooleanSupplier conditionSupplier, String message) {
throwIf(conditionSupplier, message, EXCEPTION_TYPE);
public static void throwIf(BooleanSupplier conditionSupplier, String template, Object... params) {
throwIf(conditionSupplier, StrUtil.format(template, params), EXCEPTION_TYPE);
}
}

View File

@ -22,6 +22,8 @@ import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import cn.hutool.core.util.StrUtil;
import top.charles7c.cnadmin.common.exception.BadRequestException;
/**
@ -42,11 +44,13 @@ public class ValidationUtils extends Validator {
*
* @param obj
* 被检测的对象
* @param message
* 错误信息
* @param template
* 异常信息模板被替换的部分用 {} 表示如果模板为 null返回 "null"
* @param params
* 参数值
*/
public static void throwIfNull(Object obj, String message) {
throwIfNull(obj, message, EXCEPTION_TYPE);
public static void throwIfNull(Object obj, String template, Object... params) {
throwIfNull(obj, StrUtil.format(template, params), EXCEPTION_TYPE);
}
/**
@ -54,11 +58,13 @@ public class ValidationUtils extends Validator {
*
* @param obj
* 被检测的对象
* @param message
* 错误信息
* @param template
* 异常信息模板被替换的部分用 {} 表示如果模板为 null返回 "null"
* @param params
* 参数值
*/
public static void throwIfNotNull(Object obj, String message) {
throwIfNotNull(obj, message, EXCEPTION_TYPE);
public static void throwIfNotNull(Object obj, String template, Object... params) {
throwIfNotNull(obj, StrUtil.format(template, params), EXCEPTION_TYPE);
}
/**
@ -66,11 +72,13 @@ public class ValidationUtils extends Validator {
*
* @param obj
* 被检测的对象
* @param message
* 错误信息
* @param template
* 异常信息模板被替换的部分用 {} 表示如果模板为 null返回 "null"
* @param params
* 参数值
*/
public static void throwIfEmpty(Object obj, String message) {
throwIfEmpty(obj, message, EXCEPTION_TYPE);
public static void throwIfEmpty(Object obj, String template, Object... params) {
throwIfEmpty(obj, StrUtil.format(template, params), EXCEPTION_TYPE);
}
/**
@ -78,11 +86,13 @@ public class ValidationUtils extends Validator {
*
* @param obj
* 被检测的对象
* @param message
* 错误信息
* @param template
* 异常信息模板被替换的部分用 {} 表示如果模板为 null返回 "null"
* @param params
* 参数值
*/
public static void throwIfNotEmpty(Object obj, String message) {
throwIfNotEmpty(obj, message, EXCEPTION_TYPE);
public static void throwIfNotEmpty(Object obj, String template, Object... params) {
throwIfNotEmpty(obj, StrUtil.format(template, params), EXCEPTION_TYPE);
}
/**
@ -90,11 +100,13 @@ public class ValidationUtils extends Validator {
*
* @param str
* 被检测的字符串
* @param message
* 错误信息
* @param template
* 异常信息模板被替换的部分用 {} 表示如果模板为 null返回 "null"
* @param params
* 参数值
*/
public static void throwIfBlank(CharSequence str, String message) {
throwIfBlank(str, message, EXCEPTION_TYPE);
public static void throwIfBlank(CharSequence str, String template, Object... params) {
throwIfBlank(str, StrUtil.format(template, params), EXCEPTION_TYPE);
}
/**
@ -102,11 +114,13 @@ public class ValidationUtils extends Validator {
*
* @param str
* 被检测的字符串
* @param message
* 错误信息
* @param template
* 异常信息模板被替换的部分用 {} 表示如果模板为 null返回 "null"
* @param params
* 参数值
*/
public static void throwIfNotBlank(CharSequence str, String message) {
throwIfNotBlank(str, message, EXCEPTION_TYPE);
public static void throwIfNotBlank(CharSequence str, String template, Object... params) {
throwIfNotBlank(str, StrUtil.format(template, params), EXCEPTION_TYPE);
}
/**
@ -116,11 +130,13 @@ public class ValidationUtils extends Validator {
* 要比较的对象1
* @param obj2
* 要比较的对象2
* @param message
* 错误信息
* @param template
* 异常信息模板被替换的部分用 {} 表示如果模板为 null返回 "null"
* @param params
* 参数值
*/
public static void throwIfEqual(Object obj1, Object obj2, String message) {
throwIfEqual(obj1, obj2, message, EXCEPTION_TYPE);
public static void throwIfEqual(Object obj1, Object obj2, String template, Object... params) {
throwIfEqual(obj1, obj2, StrUtil.format(template, params), EXCEPTION_TYPE);
}
/**
@ -130,11 +146,13 @@ public class ValidationUtils extends Validator {
* 要比较的对象1
* @param obj2
* 要比较的对象2
* @param message
* 错误信息
* @param template
* 异常信息模板被替换的部分用 {} 表示如果模板为 null返回 "null"
* @param params
* 参数值
*/
public static void throwIfNotEqual(Object obj1, Object obj2, String message) {
throwIfNotEqual(obj1, obj2, message, EXCEPTION_TYPE);
public static void throwIfNotEqual(Object obj1, Object obj2, String template, Object... params) {
throwIfNotEqual(obj1, obj2, StrUtil.format(template, params), EXCEPTION_TYPE);
}
/**
@ -144,11 +162,13 @@ public class ValidationUtils extends Validator {
* 要比较的字符串1
* @param str2
* 要比较的字符串2
* @param message
* 错误信息
* @param template
* 异常信息模板被替换的部分用 {} 表示如果模板为 null返回 "null"
* @param params
* 参数值
*/
public static void throwIfEqualIgnoreCase(CharSequence str1, CharSequence str2, String message) {
throwIfEqualIgnoreCase(str1, str2, message, EXCEPTION_TYPE);
public static void throwIfEqualIgnoreCase(CharSequence str1, CharSequence str2, String template, Object... params) {
throwIfEqualIgnoreCase(str1, str2, StrUtil.format(template, params), EXCEPTION_TYPE);
}
/**
@ -158,11 +178,28 @@ public class ValidationUtils extends Validator {
* 要比较的字符串1
* @param str2
* 要比较的字符串2
* @param message
* 错误信息
* @param template
* 异常信息模板被替换的部分用 {} 表示如果模板为 null返回 "null"
* @param params
* 参数值
*/
public static void throwIfNotEqualIgnoreCase(CharSequence str1, CharSequence str2, String message) {
throwIfNotEqualIgnoreCase(str1, str2, message, EXCEPTION_TYPE);
public static void throwIfNotEqualIgnoreCase(CharSequence str1, CharSequence str2, String template,
Object... params) {
throwIfNotEqualIgnoreCase(str1, str2, StrUtil.format(template, params), EXCEPTION_TYPE);
}
/**
* 如果条件成立抛出异常
*
* @param condition
* 条件
* @param template
* 异常信息模板被替换的部分用 {} 表示如果模板为 null返回 "null"
* @param params
* 参数值
*/
public static void throwIf(boolean condition, String template, Object... params) {
throwIf(condition, StrUtil.format(template, params), EXCEPTION_TYPE);
}
/**
@ -170,10 +207,12 @@ public class ValidationUtils extends Validator {
*
* @param conditionSupplier
* 条件
* @param message
* 错误信息
* @param template
* 异常信息模板被替换的部分用 {} 表示如果模板为 null返回 "null"
* @param params
* 参数值
*/
public static void throwIf(BooleanSupplier conditionSupplier, String message) {
throwIf(conditionSupplier, message, EXCEPTION_TYPE);
public static void throwIf(BooleanSupplier conditionSupplier, String template, Object... params) {
throwIf(conditionSupplier, StrUtil.format(template, params), EXCEPTION_TYPE);
}
}

View File

@ -47,7 +47,7 @@ public class Validator {
* 异常类型
*/
protected static void throwIfNull(Object obj, String message, Class<? extends RuntimeException> exceptionType) {
throwIf(() -> obj == null, message, exceptionType);
throwIf(obj == null, message, exceptionType);
}
/**
@ -61,7 +61,7 @@ public class Validator {
* 异常类型
*/
protected static void throwIfNotNull(Object obj, String message, Class<? extends RuntimeException> exceptionType) {
throwIf(() -> obj != null, message, exceptionType);
throwIf(obj != null, message, exceptionType);
}
/**
@ -75,7 +75,7 @@ public class Validator {
* 异常类型
*/
protected static void throwIfEmpty(Object obj, String message, Class<? extends RuntimeException> exceptionType) {
throwIf(() -> ObjectUtil.isEmpty(obj), message, exceptionType);
throwIf(ObjectUtil.isEmpty(obj), message, exceptionType);
}
/**
@ -89,7 +89,7 @@ public class Validator {
* 异常类型
*/
protected static void throwIfNotEmpty(Object obj, String message, Class<? extends RuntimeException> exceptionType) {
throwIf(() -> ObjectUtil.isNotEmpty(obj), message, exceptionType);
throwIf(ObjectUtil.isNotEmpty(obj), message, exceptionType);
}
/**
@ -104,7 +104,7 @@ public class Validator {
*/
protected static void throwIfBlank(CharSequence str, String message,
Class<? extends RuntimeException> exceptionType) {
throwIf(() -> StrUtil.isBlank(str), message, exceptionType);
throwIf(StrUtil.isBlank(str), message, exceptionType);
}
/**
@ -119,7 +119,7 @@ public class Validator {
*/
protected static void throwIfNotBlank(CharSequence str, String message,
Class<? extends RuntimeException> exceptionType) {
throwIf(() -> StrUtil.isNotBlank(str), message, exceptionType);
throwIf(StrUtil.isNotBlank(str), message, exceptionType);
}
/**
@ -136,7 +136,7 @@ public class Validator {
*/
protected static void throwIfEqual(Object obj1, Object obj2, String message,
Class<? extends RuntimeException> exceptionType) {
throwIf(() -> ObjectUtil.equal(obj1, obj2), message, exceptionType);
throwIf(ObjectUtil.equal(obj1, obj2), message, exceptionType);
}
/**
@ -153,7 +153,7 @@ public class Validator {
*/
protected static void throwIfNotEqual(Object obj1, Object obj2, String message,
Class<? extends RuntimeException> exceptionType) {
throwIf(() -> ObjectUtil.notEqual(obj1, obj2), message, exceptionType);
throwIf(ObjectUtil.notEqual(obj1, obj2), message, exceptionType);
}
/**
@ -170,7 +170,7 @@ public class Validator {
*/
protected static void throwIfEqualIgnoreCase(CharSequence str1, CharSequence str2, String message,
Class<? extends RuntimeException> exceptionType) {
throwIf(() -> StrUtil.equalsIgnoreCase(str1, str2), message, exceptionType);
throwIf(StrUtil.equalsIgnoreCase(str1, str2), message, exceptionType);
}
/**
@ -187,7 +187,24 @@ public class Validator {
*/
protected static void throwIfNotEqualIgnoreCase(CharSequence str1, CharSequence str2, String message,
Class<? extends RuntimeException> exceptionType) {
throwIf(() -> !StrUtil.equalsIgnoreCase(str1, str2), message, exceptionType);
throwIf(!StrUtil.equalsIgnoreCase(str1, str2), message, exceptionType);
}
/**
* 如果条件成立抛出异常
*
* @param condition
* 条件
* @param message
* 错误信息
* @param exceptionType
* 异常类型
*/
protected static void throwIf(boolean condition, String message, Class<? extends RuntimeException> exceptionType) {
if (condition) {
log.error(message);
throw ReflectUtil.newInstance(exceptionType, message);
}
}
/**

View File

@ -135,7 +135,7 @@ public class LogServiceImpl implements LogService {
@Override
public SystemLogDetailVO get(Long id) {
LogDO logDO = logMapper.selectById(id);
CheckUtils.throwIfNull(logDO, "LogDO", "ID", id);
CheckUtils.throwIfNotExists(logDO, "LogDO", "ID", id);
SystemLogDetailVO detailVO = BeanUtil.copyProperties(logDO, SystemLogDetailVO.class);
this.fill(detailVO);

View File

@ -67,7 +67,7 @@ public class DeptServiceImpl extends BaseServiceImpl<DeptMapper, DeptDO, DeptVO,
public Long add(DeptRequest request) {
String name = request.getName();
boolean isExists = this.checkNameExists(name, request.getParentId(), null);
CheckUtils.throwIf(() -> isExists, String.format("新增失败,'%s' 已存在", name));
CheckUtils.throwIf(isExists, "新增失败,[{}] 已存在", name);
request.setAncestors(this.getAncestors(request.getParentId()));
request.setStatus(DisEnableStatusEnum.ENABLE);
@ -79,20 +79,21 @@ public class DeptServiceImpl extends BaseServiceImpl<DeptMapper, DeptDO, DeptVO,
public void update(DeptRequest request, Long id) {
String name = request.getName();
boolean isExists = this.checkNameExists(name, request.getParentId(), id);
CheckUtils.throwIf(() -> isExists, String.format("修改失败,'%s' 已存在", name));
DeptDO oldDept = this.getById(id);
CheckUtils.throwIf(
() -> DisEnableStatusEnum.DISABLE.equals(request.getStatus())
&& DataTypeEnum.SYSTEM.equals(oldDept.getType()),
String.format("'%s' 是系统内置部门,不允许禁用", oldDept.getName()));
CheckUtils.throwIf(isExists, "修改失败,[{}] 已存在", name);
DeptDO oldDept = super.getById(id);
if (DataTypeEnum.SYSTEM.equals(oldDept.getType())) {
CheckUtils.throwIf(DisEnableStatusEnum.DISABLE.equals(request.getStatus()), "[{}] 是系统内置部门,不允许禁用",
oldDept.getName());
CheckUtils.throwIf(ObjectUtil.notEqual(oldDept.getParentId(), request.getParentId()),
"[{}] 是系统内置部门,不允许变更上级部门", oldDept.getName());
}
// 变更上级部门
if (ObjectUtil.notEqual(oldDept.getParentId(), request.getParentId())) {
CheckUtils.throwIf(() -> DataTypeEnum.SYSTEM.equals(oldDept.getType()),
String.format("'%s' 是系统内置部门,不允许变更上级部门", oldDept.getName()));
// 更新祖级列表
String newAncestors = this.getAncestors(request.getParentId());
request.setAncestors(newAncestors);
// 更新子级的祖级列表
this.updateChildrenAncestors(newAncestors, oldDept.getAncestors(), id);
}
super.update(request, id);
@ -104,9 +105,9 @@ public class DeptServiceImpl extends BaseServiceImpl<DeptMapper, DeptDO, DeptVO,
List<DeptDO> list =
baseMapper.lambdaQuery().select(DeptDO::getName, DeptDO::getType).in(DeptDO::getId, ids).list();
Optional<DeptDO> isSystemData = list.stream().filter(d -> DataTypeEnum.SYSTEM.equals(d.getType())).findFirst();
CheckUtils.throwIf(isSystemData::isPresent,
String.format("所选部门 '%s' 是系统内置部门,不允许删除", isSystemData.orElseGet(DeptDO::new).getName()));
CheckUtils.throwIf(() -> userService.countByDeptIds(ids) > 0, "所选部门存在用户关联,请解除关联后重试");
CheckUtils.throwIf(isSystemData::isPresent, "所选部门 [{}] 是系统内置部门,不允许删除",
isSystemData.orElseGet(DeptDO::new).getName());
CheckUtils.throwIf(userService.countByDeptIds(ids) > 0, "所选部门存在用户关联,请解除关联后重试");
// 删除部门
super.delete(ids);

View File

@ -51,7 +51,7 @@ public class MenuServiceImpl extends BaseServiceImpl<MenuMapper, MenuDO, MenuVO,
public Long add(MenuRequest request) {
String title = request.getTitle();
boolean isExists = this.checkNameExists(title, request.getParentId(), null);
CheckUtils.throwIf(() -> isExists, String.format("新增失败,'%s'已存在", title));
CheckUtils.throwIf(isExists, "新增失败,[{}] 已存在", title);
request.setStatus(DisEnableStatusEnum.ENABLE);
return super.add(request);
@ -62,7 +62,7 @@ public class MenuServiceImpl extends BaseServiceImpl<MenuMapper, MenuDO, MenuVO,
public void update(MenuRequest request, Long id) {
String title = request.getTitle();
boolean isExists = this.checkNameExists(title, request.getParentId(), id);
CheckUtils.throwIf(() -> isExists, String.format("修改失败,'%s'已存在", title));
CheckUtils.throwIf(isExists, "修改失败,[{}] 已存在", title);
super.update(request, id);
}

View File

@ -63,9 +63,9 @@ public class RoleServiceImpl extends BaseServiceImpl<RoleMapper, RoleDO, RoleVO,
@Transactional(rollbackFor = Exception.class)
public Long add(RoleRequest request) {
String name = request.getName();
CheckUtils.throwIf(() -> this.checkNameExists(name, null), String.format("新增失败,'%s'已存在", name));
CheckUtils.throwIf(this.checkNameExists(name, null), "新增失败,[{}] 已存在", name);
String code = request.getCode();
CheckUtils.throwIf(() -> this.checkCodeExists(code, null), String.format("新增失败,'%s'已存在", code));
CheckUtils.throwIf(this.checkCodeExists(code, null), "新增失败,[{}] 已存在", code);
// 新增信息
request.setStatus(DisEnableStatusEnum.ENABLE);
@ -81,17 +81,17 @@ public class RoleServiceImpl extends BaseServiceImpl<RoleMapper, RoleDO, RoleVO,
@Transactional(rollbackFor = Exception.class)
public void update(RoleRequest request, Long id) {
String name = request.getName();
CheckUtils.throwIf(() -> this.checkNameExists(name, id), String.format("修改失败,'%s'已存在", name));
CheckUtils.throwIf(this.checkNameExists(name, id), "修改失败,[{}] 已存在", name);
String code = request.getCode();
CheckUtils.throwIf(() -> this.checkCodeExists(code, id), String.format("修改失败,'%s'已存在", code));
RoleDO oldRole = this.getById(id);
CheckUtils.throwIf(this.checkCodeExists(code, id), "修改失败,[{}] 已存在", code);
RoleDO oldRole = super.getById(id);
if (DataTypeEnum.SYSTEM.equals(oldRole.getType())) {
CheckUtils.throwIf(() -> DisEnableStatusEnum.DISABLE.equals(request.getStatus()),
String.format("'%s' 是系统内置角色,不允许禁用", oldRole.getName()));
CheckUtils.throwIfNotEqual(request.getCode(), oldRole.getCode(),
String.format("'%s' 是系统内置角色,不允许修改角色编码", oldRole.getName()));
CheckUtils.throwIfNotEqual(request.getDataScope(), oldRole.getDataScope(),
String.format("'%s' 是系统内置角色,不允许修改角色数据权限", oldRole.getName()));
CheckUtils.throwIf(DisEnableStatusEnum.DISABLE.equals(request.getStatus()), "[{}] 是系统内置角色,不允许禁用",
oldRole.getName());
CheckUtils.throwIfNotEqual(request.getCode(), oldRole.getCode(), "[{}] 是系统内置角色,不允许修改角色编码",
oldRole.getName());
CheckUtils.throwIfNotEqual(request.getDataScope(), oldRole.getDataScope(), "[{}] 是系统内置角色,不允许修改角色数据权限",
oldRole.getName());
}
// 更新信息
@ -110,9 +110,9 @@ public class RoleServiceImpl extends BaseServiceImpl<RoleMapper, RoleDO, RoleVO,
List<RoleDO> list =
baseMapper.lambdaQuery().select(RoleDO::getName, RoleDO::getType).in(RoleDO::getId, ids).list();
Optional<RoleDO> isSystemData = list.stream().filter(r -> DataTypeEnum.SYSTEM.equals(r.getType())).findFirst();
CheckUtils.throwIf(isSystemData::isPresent,
String.format("所选角色 '%s' 是系统内置角色,不允许删除", isSystemData.orElseGet(RoleDO::new).getName()));
CheckUtils.throwIf(() -> userRoleService.countByRoleIds(ids) > 0, "所选角色存在用户关联,请解除关联后重试");
CheckUtils.throwIf(isSystemData::isPresent, "所选角色 [{}] 是系统内置角色,不允许删除",
isSystemData.orElseGet(RoleDO::new).getName());
CheckUtils.throwIf(userRoleService.countByRoleIds(ids) > 0, "所选角色存在用户关联,请解除关联后重试");
// 删除角色
super.delete(ids);

View File

@ -80,7 +80,7 @@ public class UserServiceImpl extends BaseServiceImpl<UserMapper, UserDO, UserVO,
public Long add(UserRequest request) {
String username = request.getUsername();
boolean isExists = this.checkNameExists(username, null);
CheckUtils.throwIf(() -> isExists, String.format("新增失败,'%s'已存在", username));
CheckUtils.throwIf(isExists, "新增失败,[{}] 已存在", username);
// 新增信息
request.setStatus(DisEnableStatusEnum.ENABLE);
@ -98,16 +98,16 @@ public class UserServiceImpl extends BaseServiceImpl<UserMapper, UserDO, UserVO,
public void update(UserRequest request, Long id) {
String username = request.getUsername();
boolean isExists = this.checkNameExists(username, id);
CheckUtils.throwIf(() -> isExists, String.format("修改失败,'%s'已存在", username));
CheckUtils.throwIf(isExists, "修改失败,[{}] 已存在", username);
UserDO oldUser = super.getById(id);
if (DataTypeEnum.SYSTEM.equals(oldUser.getType())) {
CheckUtils.throwIf(() -> DisEnableStatusEnum.DISABLE.equals(request.getStatus()),
String.format("'%s' 是系统内置用户,不允许禁用", oldUser.getNickname()));
CheckUtils.throwIf(DisEnableStatusEnum.DISABLE.equals(request.getStatus()), "[{}] 是系统内置用户,不允许禁用",
oldUser.getNickname());
List<Long> oldRoleIdList =
userRoleService.listRoleIdByUserId(id).stream().sorted().collect(Collectors.toList());
List<Long> newRoleIdList = request.getRoleIds().stream().sorted().collect(Collectors.toList());
CheckUtils.throwIf(() -> !CollUtil.isEqualList(newRoleIdList, oldRoleIdList),
String.format("'%s' 是系统内置用户,不允许变更所属角色", oldUser.getNickname()));
CheckUtils.throwIf(!CollUtil.isEqualList(newRoleIdList, oldRoleIdList), "[{}] 是系统内置用户,不允许变更所属角色",
oldUser.getNickname());
}
// 更新信息
@ -122,8 +122,8 @@ public class UserServiceImpl extends BaseServiceImpl<UserMapper, UserDO, UserVO,
List<UserDO> list =
baseMapper.lambdaQuery().select(UserDO::getNickname, UserDO::getType).in(UserDO::getId, ids).list();
Optional<UserDO> isSystemData = list.stream().filter(u -> DataTypeEnum.SYSTEM.equals(u.getType())).findFirst();
CheckUtils.throwIf(isSystemData::isPresent,
String.format("所选用户 '%s' 是系统内置用户,不允许删除", isSystemData.orElseGet(UserDO::new).getNickname()));
CheckUtils.throwIf(isSystemData::isPresent, "所选用户 [{}] 是系统内置用户,不允许删除",
isSystemData.orElseGet(UserDO::new).getNickname());
// 删除用户
super.delete(ids);
@ -147,12 +147,11 @@ public class UserServiceImpl extends BaseServiceImpl<UserMapper, UserDO, UserVO,
@Transactional(rollbackFor = Exception.class)
public String uploadAvatar(MultipartFile avatarFile, Long id) {
Long avatarMaxSizeInMb = localStorageProperties.getAvatarMaxSizeInMb();
CheckUtils.throwIf(() -> avatarFile.getSize() > avatarMaxSizeInMb * 1024 * 1024,
String.format("请上传小于 %s MB 的图片", avatarMaxSizeInMb));
CheckUtils.throwIf(avatarFile.getSize() > avatarMaxSizeInMb * 1024 * 1024, "请上传小于 {}MB 的图片", avatarMaxSizeInMb);
String avatarImageType = FileNameUtil.extName(avatarFile.getOriginalFilename());
String[] avatarSupportImgTypes = FileConsts.AVATAR_SUPPORTED_IMG_TYPES;
CheckUtils.throwIf(() -> !StrUtil.equalsAnyIgnoreCase(avatarImageType, avatarSupportImgTypes),
String.format("头像仅支持 %s 格式的图片", String.join(StringConsts.CHINESE_COMMA, avatarSupportImgTypes)));
CheckUtils.throwIf(!StrUtil.equalsAnyIgnoreCase(avatarImageType, avatarSupportImgTypes), "头像仅支持 {} 格式的图片",
String.join(StringConsts.CHINESE_COMMA, avatarSupportImgTypes));
// 上传新头像
String avatarPath = localStorageProperties.getPath().getAvatar();
@ -201,7 +200,7 @@ public class UserServiceImpl extends BaseServiceImpl<UserMapper, UserDO, UserVO,
UserDO userDO = super.getById(id);
CheckUtils.throwIfNotEqual(SecureUtils.md5Salt(currentPassword, id.toString()), userDO.getPassword(), "当前密码错误");
Long count = baseMapper.lambdaQuery().eq(UserDO::getEmail, newEmail).count();
CheckUtils.throwIf(() -> count > 0, "邮箱已绑定其他账号,请更换其他邮箱");
CheckUtils.throwIf(count > 0, "邮箱已绑定其他账号,请更换其他邮箱");
CheckUtils.throwIfEqual(newEmail, userDO.getEmail(), "新邮箱不能与当前邮箱相同");
// 更新邮箱

View File

@ -92,8 +92,7 @@ public class CaptchaController {
String captchaCacheKey = CacheConsts.CAPTCHA_CACHE_KEY;
String limitCaptchaKey = RedisUtils.formatKey(limitCacheKey, captchaCacheKey, email);
long limitTimeInMillisecond = RedisUtils.getTimeToLive(limitCaptchaKey);
CheckUtils.throwIf(() -> limitTimeInMillisecond > 0,
String.format("发送邮箱验证码过于频繁,请您 %ds 后再试", limitTimeInMillisecond / 1000));
CheckUtils.throwIf(limitTimeInMillisecond > 0, "发送邮箱验证码过于频繁,请您 {}s 后再试", limitTimeInMillisecond / 1000);
// 生成验证码
CaptchaProperties.CaptchaMail captchaMail = captchaProperties.getMail();

View File

@ -88,8 +88,7 @@ public class UserCenterController {
String rawNewPassword =
ExceptionUtils.exToNull(() -> SecureUtils.decryptByRsaPrivateKey(updatePasswordRequest.getNewPassword()));
ValidationUtils.throwIfBlank(rawNewPassword, "新密码解密失败");
ValidationUtils.throwIf(() -> !ReUtil.isMatch(RegExpConsts.PASSWORD, rawNewPassword),
"密码长度 6 到 32 位,同时包含数字和字母");
ValidationUtils.throwIf(!ReUtil.isMatch(RegExpConsts.PASSWORD, rawNewPassword), "密码长度 6 到 32 位,同时包含数字和字母");
// 修改密码
userService.updatePassword(rawOldPassword, rawNewPassword, LoginHelper.getUserId());