SpringBoot(13) - - SpringBoot 自定义异常处理

项目路径:https://github.com/zhaopeng01/springboot-study/tree/master/study_13

序言

在代码中使用自定义的异常类,可以结合自己的项目对异常进行统一的封装处理,进行封装管理,使得整个项目的异常处理更规范、更统一、更优雅。同时,使得日志的记录上更加清晰,便于后续查日志定位问题。
所以这篇文章就来写一下自定义异常的处理方式,都是根据自己的个人的一些想法去写的

依赖

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.7</version>
        </dependency>
        <dependency>
            <groupId>com.googlecode.libphonenumber</groupId>
            <artifactId>libphonenumber</artifactId>
            <version>8.9.13</version>
        </dependency>
    </dependencies>

常用校验方法

把一些常用的校验方法放到了一起,算是一种整合吧,感觉能用到的都放进去了,再有继续补充


/**
 * Assertion utility class that assists in validating arguments.
 *
 */
public abstract class Assert {
   
    private static String getMessage(String key, Object... args) {
   
        return Resources.getMessage(key, args);
    }

    /**  */
    public static void isTrue(boolean expression, String key) {
   
        if (!expression) {
   
            throw new IllegalArgumentException(getMessage(key));
        }
    }

    /**  */
    public static void isNull(Object object, String key) {
   
        if (object != null) {
   
            throw new IllegalArgumentException(getMessage(key));
        }
    }

    /**
     * (key_IS_NULL)
     */
    public static void notNull(Object object, String key, Object... args) {
   
        if (object == null) {
   
            throw new IllegalArgumentException(getMessage(key + "_IS_NULL", args));
        }
    }

    /**  */
    public static void hasLength(String text, String key) {
   
        if (StringUtils.isEmpty(text)) {
   
            throw new IllegalArgumentException(getMessage(key));
        }
    }

    /**  */
    public static void hasText(String text, String key) {
   
        if (StringUtils.isBlank(text)) {
   
            throw new IllegalArgumentException(getMessage(key));
        }
    }

    /**  */
    public static void doesNotContain(String textToSearch, String substring, String key) {
   
        if (StringUtils.isNotBlank(textToSearch) && StringUtils.isNotBlank(substring)
                && textToSearch.contains(substring)) {
   
            throw new IllegalArgumentException(getMessage(key));
        }
    }

    /** */
    public static void notEmpty(Object[] array, String key, Object... args) {
   
        if (ObjectUtils.isEmpty(array)) {
   
            throw new IllegalArgumentException(getMessage(key + "_IS_EMPTY", args));
        }
    }

    /**  */
    public static void noNullElements(Object[] array, String key) {
   
        if (array != null) {
   
            for (Object element : array) {
   
                if (element == null) {
   
                    throw new IllegalArgumentException(getMessage(key));
                }
            }
        }
    }

    /**  */
    public static void notEmpty(Collection<?> collection, String key) {
   
        if (CollectionUtils.isEmpty(collection)) {
   
            throw new IllegalArgumentException(getMessage(key));
        }
    }

    /**  */
    public static void notEmpty(Map<?, ?> map, String key) {
   
        if (CollectionUtils.isEmpty(map)) {
   
            throw new IllegalArgumentException(getMessage(key));
        }
    }

    /**  */
    public static void isInstanceOf(Class<?> type, Object obj, String key) {
   
        notNull(type, key);
        if (!type.isInstance(obj)) {
   
            throw new IllegalArgumentException(getMessage(key));
        }
    }

    /**  */
    public static void isAssignable(Class<?> superType, Class<?> subType, String key) {
   
        notNull(superType, key);
        if (subType == null || !superType.isAssignableFrom(subType)) {
   
            throw new IllegalArgumentException(getMessage(key));
        }
    }

    /**
     * 空字符或NULL
     */
    public static void isBlank(String text, String key) {
   
        if (StringUtils.isNotBlank(text)) {
   
            throw new IllegalArgumentException(getMessage(key));
        }
    }

    /**
     * 非空字符串(key_IS_NULL)
     */
    public static void isNotBlank(String text, String key) {
   
        if (StringUtils.isBlank(text)) {
   
            throw new IllegalArgumentException(getMessage(key + "_IS_NULL"));
        }
    }

    /**
     * 允许最小值
     */
    public static void min(Integer value, Integer min, String key) {
   
        notNull(value, key);
        if (value < min) {
   
            throw new IllegalArgumentException(getMessage(key + "_MIN", min));
        }
    }

    /**
     * 允许最大值
     */
    public static void max(Integer value, Integer max, String key) {
   
        notNull(value, key);
        if (value > max) {
   
            throw new IllegalArgumentException(getMessage(key + "_MAX", max));
        }
    }

    /**
     * 允许值范围
     */
    public static void range(Integer value, Integer min, Integer max, String key) {
   
        min(value, min, key);
        max(value, max, key);
    }

    /**
     * 允许最小值
     */
    public static void min(Float value, Float min, String key) {
   
        notNull(value, key);
        if (value < min) {
   
            throw new IllegalArgumentException(getMessage(key + "_MIN", min));
        }
    }

    /**
     * 允许最大值
     */
    public static void max(Float value, Float max, String key) {
   
        notNull(value, key);
        if (value > max) {
   
            throw new IllegalArgumentException(getMessage(key + "_MAX", max));
        }
    }

    /**
     * 允许值范围
     */
    public static void range(Float value, Float min, Float max, String key) {
   
        min(value, min, key);
        max(value, max, key);
    }

    /**
     * 允许最小值
     */
    public static void min(Double value, Double min, String key) {
   
        notNull(value, key);
        if (value < min) {
   
            throw new IllegalArgumentException(getMessage(key + "_MIN", min));
        }
    }

    /**
     * 允许最大值
     */
    public static void max(Double value, Double max, String key) {
   
        notNull(value, key);
        if (value > max) {
   
            throw new IllegalArgumentException(getMessage(key + "_MAX", max));
        }
    }

    /**
     * 允许值范围
     */
    public static void range(Double value, Double min, Double max, String key) {
   
        min(value, min, key);
        max(value, max, key);
    }

    /**
     * 字符长度(key_LENGTH)
     */
    public static void length(String text, Integer min, Integer max, String key) {
   
        notNull(text, key);
        if (min != null && text.length() < min) {
   
            throw new IllegalArgumentException(getMessage(key + "_LENGTH", min, max));
        }
        if (max != null && text.length() > max) {
   
            throw new IllegalArgumentException(getMessage(key + "_LENGTH", min, max));
        }
    }

    /**
     * 未来某一天
     */
    public static void future(Date date, String key) {
   
        if (date != null && date.compareTo(new Date()) <= 0) {
   
            throw new IllegalArgumentException(getMessage(key + "_NOT_FUTURE"));
        }
    }

    /**
     * 身份证
     */
    public static void idCard(String text) {
   
        if (!IDCardUtil.isIdentity(text)) {
   
            throw new IllegalArgumentException(getMessage("IDCARD_ILLEGAL"));
        }
    }

    /**
     * 邮箱
     */
    public static void email(String text) {
   
        String regex = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        pattern(text, regex, true, "EMAIL");
    }

    /**
     * 手机号
     */
    public static void mobile(String text) {
   
        String regex = "((^(13|15|17|18)[0-9]{9}$)|(^0[1,2]{1}\\d{1}-?\\d{8}$)|(^0[3-9] {1}\\d{2}-?\\d{7,8}$)|(^0[1,2]{1}\\d{1}-?\\d{8}-(\\d{1,4})$)|(^0[3-9]{1}\\d{2}-? \\d{7,8}-(\\d{1,4})$))";
        pattern(text, regex, true, "MOBILE");
    }

    /**
     * 正则表达式
     */
    public static void pattern(String text, String regex, boolean flag, String key) {
   
        boolean result = false;
        try {
   
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(text);
            result = matcher.matches();
        } catch (Exception e) {
   
            result = false;
        }
        if (result != flag) {
   
            throw new IllegalArgumentException(getMessage(key + "_ILLEGAL"));
        }
    }


    /**
     * 邮箱
     */
    public static String password(String password) {
   
        password = password.trim();
        pattern(password, "(?![0-9]+)([A-Za-z0-9]{8,16})", true, "PASSWORD");
        return password;
    }

    public static String userName(String userName) {
   
        userName = userName.trim();
        if (userName.length() > 7) {
   
            throw new IllegalArgumentException(getMessage("USER_NAME_ILLEGAL"));
        }
        return userName;
    }

    public static String userInfo(String userInfo) {
   
        userInfo = userInfo.trim();
        if (userInfo.length() > 150) {
   
            throw new IllegalArgumentException(getMessage("USER_INFO_ILLEGAL"));
        }
        return userInfo;
    }

    public static String payPassword(String password) {
   
        password = password.trim();
        pattern(password, "[0-9]{6}", true, "PAY_PASSWORD");
        return password;
    }

    public static void confirmTheCurrentRole(Integer currentRole, Integer actualRole) {
   
        if (!currentRole.equals(actualRole)) {
   
            throw new IllegalArgumentException(getMessage("INCONSISTENT_CURRENT_ROLE"));
        }
    }
    

    /**
     * 手机号
     */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值