Skip to content

Commit 9566a23

Browse files
committed
添加断言工具类,简化代码
1 parent 21daaf4 commit 9566a23

File tree

10 files changed

+256
-66
lines changed

10 files changed

+256
-66
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.tang.commons.exception;
2+
3+
/**
4+
* 断言异常
5+
*
6+
* @author Tang
7+
*/
8+
public class AssertException extends RuntimeException {
9+
10+
@java.io.Serial
11+
private static final long serialVersionUID = 1953209867997857028L;
12+
13+
public AssertException() {
14+
}
15+
16+
public AssertException(String message) {
17+
super(message);
18+
}
19+
20+
public AssertException(Throwable cause) {
21+
super(cause);
22+
}
23+
24+
public AssertException(String message, Throwable cause) {
25+
super(message, cause);
26+
}
27+
28+
}
Lines changed: 182 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,182 @@
1+
package com.tang.commons.utils;
2+
3+
import java.util.Objects;
4+
import java.util.function.Supplier;
5+
6+
import com.tang.commons.exception.AssertException;
7+
8+
/**
9+
* 断言工具类,符合条件时抛出异常
10+
*
11+
* @author Tang
12+
*/
13+
public class Assert {
14+
15+
private Assert() {
16+
}
17+
18+
/**
19+
* 表达式为 True 时抛出异常
20+
*
21+
* @param expression 表达式
22+
*/
23+
public static void isTrue(boolean expression) {
24+
isTrue(expression, "表达式为 True");
25+
}
26+
27+
/**
28+
* 表达式为 True 时抛出异常
29+
*
30+
* @param expression 表达式
31+
* @param message 异常信息
32+
*/
33+
public static void isTrue(boolean expression, String message) {
34+
isTrue(expression, new AssertException(message));
35+
}
36+
37+
/**
38+
* 表达式为 True 时抛出异常
39+
*
40+
* @param expression 表达式
41+
* @param cause 异常
42+
*/
43+
public static void isTrue(boolean expression, RuntimeException cause) {
44+
isTrue(expression, () -> cause);
45+
}
46+
47+
/**
48+
* 表达式为 True 时抛出异常
49+
*
50+
* @param expression 表达式
51+
* @param cause 异常
52+
*/
53+
public static void isTrue(boolean expression, Supplier<? extends RuntimeException> cause) {
54+
if (expression) {
55+
throw cause.get();
56+
}
57+
}
58+
59+
/**
60+
* 表达式为 False 时抛出异常
61+
*
62+
* @param expression 表达式
63+
*/
64+
public static void isFalse(boolean expression) {
65+
isFalse(expression, "表达式为 False");
66+
}
67+
68+
/**
69+
* 表达式为 False 时抛出异常
70+
*
71+
* @param expression 表达式
72+
* @param message 异常信息
73+
*/
74+
public static void isFalse(boolean expression, String message) {
75+
isFalse(expression, new AssertException(message));
76+
}
77+
78+
/**
79+
* 表达式为 False 时抛出异常
80+
*
81+
* @param expression 表达式
82+
* @param cause 异常
83+
*/
84+
public static void isFalse(boolean expression, RuntimeException cause) {
85+
isFalse(expression, () -> cause);
86+
}
87+
88+
/**
89+
* 表达式为 False 时抛出异常
90+
*
91+
* @param expression 表达式
92+
* @param cause 异常
93+
*/
94+
public static void isFalse(boolean expression, Supplier<? extends RuntimeException> cause) {
95+
if (!expression) {
96+
throw cause.get();
97+
}
98+
}
99+
100+
/**
101+
* 对象为 Null 时抛出异常
102+
*
103+
* @param object 对象
104+
*/
105+
public static void isNull(Object object) {
106+
isNull(object, "对象为 Null");
107+
}
108+
109+
/**
110+
* 对象为 Null 时抛出异常
111+
*
112+
* @param object 对象
113+
* @param message 异常信息
114+
*/
115+
public static void isNull(Object object, String message) {
116+
isNull(object, new AssertException(message));
117+
}
118+
119+
/**
120+
* 对象为 Null 时抛出异常
121+
*
122+
* @param object 对象
123+
* @param cause 异常
124+
*/
125+
public static void isNull(Object object, RuntimeException cause) {
126+
isNull(object, () -> cause);
127+
}
128+
129+
/**
130+
* 对象为 Null 时抛出异常
131+
*
132+
* @param object 对象
133+
* @param cause 异常
134+
*/
135+
public static void isNull(Object object, Supplier<? extends RuntimeException> cause) {
136+
if (Objects.isNull(object)) {
137+
throw cause.get();
138+
}
139+
}
140+
141+
/**
142+
* 对象不为 Null 时抛出异常
143+
*
144+
* @param object 对象
145+
*/
146+
public static void nonNull(Object object) {
147+
nonNull(object, "对象不为 Null");
148+
}
149+
150+
/**
151+
* 对象不为 Null 时抛出异常
152+
*
153+
* @param object 对象
154+
* @param message 异常信息
155+
*/
156+
public static void nonNull(Object object, String message) {
157+
nonNull(object, new AssertException(message));
158+
}
159+
160+
/**
161+
* 对象不为 Null 时抛出异常
162+
*
163+
* @param object 对象
164+
* @param cause 异常
165+
*/
166+
public static void nonNull(Object object, RuntimeException cause) {
167+
nonNull(object, () -> cause);
168+
}
169+
170+
/**
171+
* 对象不为 Null 时抛出异常
172+
*
173+
* @param object 对象
174+
* @param cause 异常
175+
*/
176+
public static void nonNull(Object object, Supplier<? extends RuntimeException> cause) {
177+
if (Objects.nonNull(object)) {
178+
throw cause.get();
179+
}
180+
}
181+
182+
}

tang-commons/src/main/java/com/tang/commons/utils/SqlUtils.java

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,7 @@ private SqlUtils() {
2323
* 检查字符,防止注入绕过
2424
*/
2525
public static String escapeOrderBySql(String value) {
26-
if (StringUtils.isNotBlank(value) && !isValidOrderBySql(value)) {
27-
throw new UtilsException("查询失败, 参数不符合规范");
28-
}
26+
Assert.isTrue(StringUtils.isNotBlank(value) && !isValidOrderBySql(value), new UtilsException("查询失败, 参数不符合规范"));
2927
return value;
3028
}
3129

tang-commons/src/main/java/com/tang/commons/utils/UploadsUtils.java

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -84,24 +84,24 @@ public static String uploadAvatar(MultipartFile avatar) {
8484
*/
8585
private static String upload(MultipartFile file, String path) {
8686
var fileName = getFileName(file);
87-
if (fileName.length() > MAX_FILE_NAME_LENGTH) {
88-
throw new MaxFileNameLengthException("上传失败, 文件名最大长度为: " + MAX_FILE_NAME_LENGTH);
89-
}
90-
if (file.getSize() > MAX_FILE_SIZE) {
91-
throw new MaxFileSizeException("上传失败, 文件最大大小为: " + ByteUtils.getSize(MAX_FILE_SIZE));
92-
}
87+
88+
Assert.isTrue(fileName.length() > MAX_FILE_NAME_LENGTH, new MaxFileNameLengthException("上传失败, 文件名最大长度为: " + MAX_FILE_NAME_LENGTH));
89+
Assert.isTrue(file.getSize() > MAX_FILE_SIZE, new MaxFileSizeException("上传失败, 文件最大大小为: " + ByteUtils.getSize(MAX_FILE_SIZE)));
90+
9391
fileName = System.currentTimeMillis() + "_" + fileName;
9492
var destDir = new File(path);
9593
if (!destDir.exists()) {
9694
destDir.mkdirs();
9795
}
9896
var filePath = destDir + File.separator + fileName;
9997
var dest = new File(filePath);
98+
10099
try {
101100
file.transferTo(dest);
102101
} catch (IllegalStateException | IOException e) {
103102
LOGGER.error("上传文件失败, 文件路径: {}, 文件大小: {}", filePath, ByteUtils.getSize(file.getSize()), e);
104103
}
104+
105105
filePath = filePath.replace("\\", "/");
106106
if (LOGGER.isInfoEnabled()) {
107107
LOGGER.info("上传文件成功, 文件路径: {}, 文件大小: {}", filePath, ByteUtils.getSize(file.getSize()));

tang-commons/src/main/java/com/tang/commons/utils/date/DateUtils.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
import java.time.temporal.ChronoUnit;
88
import java.util.Locale;
99

10+
import com.tang.commons.utils.Assert;
11+
1012
/**
1113
* 日期工具类
1214
*
@@ -41,9 +43,7 @@ public static String getChatTime(LocalDateTime localDateTime, boolean is12HourFo
4143
var monday = now.with(DayOfWeek.MONDAY).truncatedTo(ChronoUnit.DAYS);
4244
var sunday = monday.plusDays(6);
4345

44-
if (localDateTime.toLocalDate().isAfter(now.toLocalDate())) {
45-
throw new IllegalArgumentException("Chat time cannot be later than now");
46-
}
46+
Assert.isTrue(localDateTime.toLocalDate().isAfter(now.toLocalDate()), new IllegalArgumentException("Chat time cannot be later than now"));
4747

4848
var pattern = new StringBuilder();
4949

tang-commons/src/main/java/com/tang/commons/utils/id/Snowflake.java

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package com.tang.commons.utils.id;
22

3+
import com.tang.commons.utils.Assert;
4+
35
/**
46
* 雪花算法
57
*
@@ -84,12 +86,9 @@ public class Snowflake {
8486
* @param machineId 机器标识
8587
*/
8688
public Snowflake(long dataCenterId, long machineId) {
87-
if (dataCenterId > MAX_DATA_CENTER_NUM || dataCenterId < 0) {
88-
throw new IllegalArgumentException("Data center ID can't be greater than MAX_DATA_CENTER_NUM or less than 0");
89-
}
90-
if (machineId > MAX_MACHINE_NUM || machineId < 0) {
91-
throw new IllegalArgumentException("Machine ID can't be greater than MAX_MACHINE_NUM or less than 0");
92-
}
89+
Assert.isTrue(dataCenterId > MAX_DATA_CENTER_NUM || dataCenterId < 0, new IllegalArgumentException("Data center ID can't be greater than MAX_DATA_CENTER_NUM or less than 0"));
90+
Assert.isTrue(machineId > MAX_MACHINE_NUM || machineId < 0, new IllegalArgumentException("Machine ID can't be greater than MAX_MACHINE_NUM or less than 0"));
91+
9392
this.dataCenterId = dataCenterId;
9493
this.machineId = machineId;
9594
}
@@ -101,10 +100,8 @@ public Snowflake(long dataCenterId, long machineId) {
101100
*/
102101
public synchronized long nextId() {
103102
long currentTimestamp = getTimestamp();
104-
if (currentTimestamp < lastTimestamp) {
105-
// 如果当前时间小于上一次ID生成的时间戳,说明系统时钟回退过,抛出非法异常
106-
throw new IllegalArgumentException("Clock moved backwards. Refusing to generate id");
107-
}
103+
// 如果当前时间小于上一次ID生成的时间戳,说明系统时钟回退过,抛出非法异常
104+
Assert.isTrue(currentTimestamp < lastTimestamp, new IllegalArgumentException("Clock moved backwards. Refusing to generate id"));
108105

109106
// 如果是同一时间生成的,则进行毫秒内序列
110107
if (currentTimestamp == lastTimestamp) {

tang-commons/src/main/java/com/tang/commons/utils/poi/ExcelUtils.java

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
import com.tang.commons.exception.file.FileNotExistException;
3737
import com.tang.commons.exception.file.FileTypeMismatchException;
3838
import com.tang.commons.model.SysDictDataModel;
39+
import com.tang.commons.utils.Assert;
3940
import com.tang.commons.utils.DictUtils;
4041
import com.tang.commons.utils.LogUtils;
4142

@@ -61,15 +62,19 @@ private ExcelUtils() {
6162
* @return 数据
6263
*/
6364
public static <T> List<T> importExcel(Class<T> clazz, MultipartFile file) {
64-
if (Objects.isNull(file)) {
65+
Assert.isNull(file, () -> {
6566
LOGGER.error("导入失败, 文件为空");
66-
throw new FileNotExistException("导入失败, 文件为空");
67-
}
67+
return new FileNotExistException("导入失败, 文件为空");
68+
});
6869
var fileName = file.getOriginalFilename();
69-
if (Objects.isNull(fileName) || !fileName.endsWith(FileType.EXCEL_2007)) {
70+
Assert.isNull(fileName, () -> {
71+
LOGGER.error("导入失败, 文件名为空");
72+
return new FileNotExistException("导入失败, 文件名为空");
73+
});
74+
Assert.isFalse(fileName.endsWith(FileType.EXCEL_2007), () -> {
7075
LOGGER.error("导入失败, 只支持 Excel 2007 及以上版本");
71-
throw new FileTypeMismatchException("导入失败, 只支持 Excel 2007 及以上版本");
72-
}
76+
return new FileTypeMismatchException("导入失败, 只支持 Excel 2007 及以上版本");
77+
});
7378

7479
var list = new ArrayList<T>();
7580
var fields = getFields(clazz);

tang-framework/src/main/java/com/tang/framework/web/service/LoginService.java

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
import com.tang.commons.exception.user.IllegalLoginTypeException;
1818
import com.tang.commons.model.LoginModel;
1919
import com.tang.commons.model.UserModel;
20+
import com.tang.commons.utils.Assert;
2021
import com.tang.commons.utils.LogUtils;
2122
import com.tang.commons.utils.RedisUtils;
2223
import com.tang.commons.utils.StringUtils;
@@ -123,13 +124,8 @@ public void verifyCaptcha(LoginModel loginModel) {
123124

124125
var captcha = redisUtils.get(CachePrefix.CAPTCHA + loginModel.getCaptcha().getId());
125126

126-
if (Objects.isNull(captcha)) {
127-
throw new CaptchaException("验证码已过期");
128-
}
129-
130-
if (!captcha.equals(loginModel.getCaptcha().getText())) {
131-
throw new CaptchaException("验证码错误");
132-
}
127+
Assert.isNull(captcha, new CaptchaException("验证码已过期"));
128+
Assert.isFalse(captcha.equals(loginModel.getCaptcha().getText()), new CaptchaException("验证码错误"));
133129
}
134130

135131
}

tang-framework/src/main/java/com/tang/framework/web/service/authentication/AuthenticationService.java

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
import com.tang.commons.model.SysDeptModel;
1515
import com.tang.commons.model.SysUserModel;
1616
import com.tang.commons.model.UserModel;
17+
import com.tang.commons.utils.Assert;
1718
import com.tang.commons.utils.SecurityUtils;
1819
import com.tang.framework.web.service.TokenService;
1920
import com.tang.system.entity.SysUser;
@@ -59,18 +60,10 @@ public AuthenticationService(SysRoleService roleService, SysMenuService menuServ
5960
*/
6061
public UserModel createUserModel(SysUser user, String password, String account, String loginType) {
6162
try {
62-
if (Objects.isNull(user)) {
63-
throw new UserNotFoundException("用户不存在");
64-
}
65-
if (!SecurityUtils.matchesPassword(password, user.getPassword())) {
66-
throw new PasswordMismatchException("密码错误");
67-
}
68-
if (user.getStatus().equals(Status.DISABLED)) {
69-
throw new DisabledException("账号已停用");
70-
}
71-
if (user.getDelFlag().equals(Status.DELETED)) {
72-
throw new DeletedException("账号已删除");
73-
}
63+
Assert.isNull(user, new UserNotFoundException("用户不存在"));
64+
Assert.isFalse(SecurityUtils.matchesPassword(password, user.getPassword()), new PasswordMismatchException("密码错误"));
65+
Assert.isTrue(user.getStatus().equals(Status.DISABLED), new DisabledException("账号已停用"));
66+
Assert.isTrue(user.getDelFlag().equals(Status.DELETED),new DeletedException("账号已删除"));
7467
} catch (RuntimeException e) {
7568
logLoginService.recordLoginInfo(Objects.isNull(user) ? null : user.getUserId(), tokenService.getUserAgent(), account, loginType, false, e.getMessage());
7669
throw e;

0 commit comments

Comments
 (0)