Springboot 使用断言Assert方式来校验业务的异常情况,消除 if else语句

1、什么是断言

断言(assert)是一种编程中常用的手段。在通常情况下,断言就是将一个返回值总是需要为真的判别式放在语句中,用于排除在设计的逻辑上不应该产生的情况。比如一个函数总需要输入在一定的范围内的参数,那么程序员就可以对该参数使用断言,以迫使在该参数发生异常的时候程序退出,从而避免程序陷入逻辑的混乱。
源码:https://gitee.com/charlinchenlin/store-pos

2、使用断言比使用if else更简洁

test2使用断言代替if 语句

public class AssertTests {

	//if else的用法
    @Test
    public void test1() {
        Object o = null;
        if (o == null) {
            throw new IllegalArgumentException("用户不存在.");
        }
    }

	//断言的用法:更为简洁
    @Test
    public void test2() {
        // 另一种写法
        Object o = null;
        Assert.notNull(o, "用户不存在.");
    }
}

3、自定义断言

用断言的方式封装异常的抛出

@Slf4j
public abstract class MyAssert {

    /**
     * 断言对象不为空
     * 如果对象obj为空,则抛出异常
     * @param obj 待判断对象
     */
    public static void notNull(Object obj, ResponseEnum responseEnum) {
        if (obj == null) {
            log.info("obj is null...............");
            throw new MyException(responseEnum);
        }
    }
    
	public static void notNull(Object obj, String msg) {
        if (obj == null) {
            log.info("obj is null...............");
            throw new MyException(msg);
        }
    }
	 /**
     * 断言对象为空
     * 如果对象obj不为空,则抛出异常
     *
     * @param object
     * @param responseEnum
     */
    public static void isNull(Object object, ResponseEnum responseEnum) {
        if (object != null) {
            log.info("obj is not null......");
            throw new MyException(responseEnum);
        }
    }

    /**
     * 断言表达式为真
     * 如果不为真,则抛出异常
     *
     * @param expression 是否成功
     */
    public static void isTrue(boolean expression, ResponseEnum responseEnum) {
        if (!expression) {
            log.info("fail...............");
            throw new MyException(responseEnum);
        }
    }

    /**
     * 断言两个对象不相等
     * 如果相等,则抛出异常
     *
     * @param m1
     * @param m2
     * @param responseEnum
     */
    public static void notEquals(Object m1, Object m2, ResponseEnum responseEnum) {
        if (m1.equals(m2)) {
            log.info("equals...............");
            throw new MyException(responseEnum);
        }
    }

    /**
     * 断言两个对象相等
     * 如果不相等,则抛出异常
     *
     * @param m1
     * @param m2
     * @param responseEnum
     */
    public static void equals(Object m1, Object m2, ResponseEnum responseEnum) {
        if (!m1.equals(m2)) {
            log.info("not equals...............");
            throw new MyException(responseEnum);
        }
    }

    /**
     * 断言参数不为空
     * 如果为空,则抛出异常
     *
     * @param s
     * @param responseEnum
     */
    public static void notEmpty(String s, ResponseEnum responseEnum) {
        if (StringUtils.isEmpty(s)) {
            log.info("is empty...............");
            throw new MyException(responseEnum);
        }
    }
}

MyException 代码

@Data
@NoArgsConstructor
public class MyException extends RuntimeException{

    //错误码
    private Integer code;
    //错误信息
    private String msg;

    public MyException(String msg){
        this.msg = msg;
    }

    public MyException(Integer code, String msg){
        this.msg = msg;
        this.code = code;
    }

    public MyException(Integer code, String msg, Throwable cause){
        super(cause);
        this.msg = msg;
        this.code = code;
    }

    public MyException(ResponseEnum responseEnum){
        this.code = responseEnum.getCode();
        this.msg = responseEnum.getMsg();
    }
}

响应信息ResponseEnum

@Getter
@ToString
@AllArgsConstructor
public enum ResponseEnum {

    SUCCESS(0, "成功"),
    ERROR(-1, "服务器内部错误"),
    //-1xx 服务器错误
    BAD_SQL_GRAMMAR_ERROR(-101, "sql语法错误"),
    SERVLET_ERROR(-102, "servlet请求异常"), //-2xx 参数校验   
    ;

    //响应状态码
    private Integer code;
    //响应信息
    private String message;
}

4、自定义断言使用

  • 校验手机号吗不能为空
  • 是否是合法的手机号码
  • 手机号是否注册
 @ApiOperation("获取验证码")
    @GetMapping("/send/{mobile}")
    public R send(@ApiParam(value = "手机号", required = true)  @PathVariable String mobile) {

        //校验手机号吗不能为空
        MyAssert.notEmpty(mobile, ResponseEnum.MOBILE_NULL_ERROR);
        //是否是合法的手机号码
        MyAssert.isTrue(RegexValidateUtils.checkCellphone(mobile), ResponseEnum.MOBILE_ERROR);
        //手机号是否注册
        boolean result = userService.checkMobile(mobile);
        System.out.println("result = " + result);     
        MyAssert.isTrue(result == false, ResponseEnum.MOBILE_EXIST_ERROR);

        String code = RandomUtils.getFourBitRandom();
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", code);
        //调用阿里云手机短信服务,发送验证码到手机
        smsService.send(mobile, SmsProperties.TEMPLATE_CODE, map);

        //将验证码存入redis
        redisTemplate.opsForValue().set(SysConst.REDIS_SMS_CODE + mobile, code, 5, TimeUnit.MINUTES);

        return R.ok().message("短信发送成功");
    }

5、详情请看源码

https://gitee.com/charlinchenlin/store-pos

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lovoo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值