統一處理"將截斷字符串或二進制數據"異常

該錯誤是字段過長的原因, 對應的異常類型是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 = "你輸入的內容過多!";
}

本文到此結束

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章