统一处理"将截断字符串或二进制数据"异常

该错误是字段过长的原因, 对应的异常类型是DataTruncation. 因为在实际场景中,没有必要把所有字段都用最长字符, 会造成不必要的资源浪费. 但是通过代码一一去控制长度又不够优雅.我们可以通过在捕获异常时,针对这个异常,进行处理/提示.

1.定义一个工具类,用于在异常链中获取异常

public class ExceptionUtils {

    /**
     * 从异常的异常链中获取指定类型的错误.
     */
    public static Throwable getTargetException(Exception e, Class<?> targetE) {
        if (e == null) return e;
        Throwable throwable = e.getCause();
        while (throwable != null && !throwable.getClass().isAssignableFrom(targetE)) {
            throwable = throwable.getCause();
        }
        return throwable;
    }
}

2.在异常处理中进行特殊处理即可

Throwable t = ExceptionUtils.getTargetException(ex, DataTruncation.class);
if(t != null && t instanceof DataTruncation) {
	msg = "你输入的内容过多!";
}

本文到此结束

发布了60 篇原创文章 · 获赞 5 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_40085888/article/details/105148183
今日推荐