先来看以下两段代码
package com.zst.asserts;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
@Service
public class LoginService {
public void login(String name, String password) {
if (name == null || name.isEmpty()) {
throw new RuntimeException("请输⼊⽤⼾名");
}
if (password == null || password.isEmpty()) {
throw new RuntimeException("请输⼊密码");
}
.....
}
}
package com.zst.asserts;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
@Service
public class LoginService {
public void login(String name, String password) {
Assert.notNull(name, "请输⼊⽤⼾名");
Assert.notNull(password, "请输⼊密码");
......
}
}
上面两段代码都是判断用户名和密码是否为空,如果name或者password的值为null,就会抛出异常。第二端代码,看着是不是清爽了很多 O(∩_∩)O哈哈~
⼀. 断⾔
在上述代码中,我们其实使⽤了Spring中的断⾔类。
断⾔(assert)其实是jdk 1.4中提供的⼀个关键字,使⽤断⾔,可以实现对数据的快速验证。 Assert类借助了该思想,优雅地实现了数据的验证。
我们来看看Assert类中notNull()⽅法的源码:
现在你看到了,该⽅法的实现很简单,满⾜判断条件,就抛出IllegalArgumentException异常。Assert 类中还有很多其他的⽅法,它们的实现思想都是⼀模⼀样的。 但是这样写,只能抛出IllegalArgumentException异常,⽽且不能根据特定类型的数据进⾏更全⾯的 判断。如果我们想进⾏定制,想要抛出⾃定义的异常,还需要我们⾃⼰动⼿,丰⾐⾜⻝。
⼆. ⾃定义断⾔类
1. ⾃定义异常类
通常情况下,我们都会在项⽬中⾃定义⾃⼰的异常类,⽤于处理各种异常信息。
package com.zst.asserts;
/**
* ⾃定义异常类
*/
public class MyException extends RuntimeException {
/**
* 异常编码
*/
private int code;
/**
* 异常信息
*/
private String msg;
public MyException(int code, String msg) {
this.code = code;
this.msg = msg;
}
}
2. ⾃定义断⾔类
package com.zst.asserts;
/**
* ⾃定义断⾔类
*/
public class MyAssert {
/**
* 如果待判断的数据为null,抛出异常
* @param info
* @param message
*/
public static void assertNotEmpty(String info, String message) {
if (info == null || info.trim().isEmpty()) {
throw new MyException(CommonConstants.ERROR, message);
}
}
}
3. 测试
package com.zst.asserts;
import org.springframework.stereotype.Service;
@Service
public class LoginService {
public void login(String name, String password) {
MyAssert.assertNotEmpty(name, "请输⼊⽤⼾名");
MyAssert.assertNotEmpty(password, "请输⼊密码");
......
}
}