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