Valid 註解校驗數字轉化異常提示訊息更改

2021-09-22 23:06:51 字數 701 閱讀 4827

當專案中使用 @valid 對表單進行校驗,對integer 型別校驗的最小值、最大值等都無法避免對該型別輸入字串的錯誤提示,即向前端返回數字轉化異常的明文**,對使用者的顯示特別不友好。

通過設定全域性異常捕獲機制,將 bindexception進行捕獲,若異常型別為數字轉化異常,即提示該欄位格式不正確。

@exceptionhandler(value = constraintviolationexception.class)

public serverresponse constraintviolationexceptionhandler(constraintviolationexception ex)

@exceptionhandler(value = bindexception.class)

public serverresponse bindexceptionhandler(bindexception ex)

}return fielderror.getdefaultmessage();

}).collect(collectors.joining("、","您填寫的資訊共有"+ex.getfielderrors().size()+"項錯誤:",""));

return serverresponse.createbyerrormessage(msglist);

}

Spring 引數校驗 Valid註解

null 限制只能為null notnull 限制必須不為null assertfalse 限制必須為false asserttrue 限制必須為true decimalmax value 限制必須為乙個不大於指定值的數字 decimalmin value 限制必須為乙個不小於指定值的數字 digi...

Valid註解的使用

在實體類上打上註解 data public class user2.在controller上加上註解 valid,進行引數校驗 public string testuser requestbody valid user user,bindingresult bindingresult return ...

Valid註解的作用

用於驗證註解是否符合要求,直接加在變數user之前,在變數中新增驗證資訊的要求,當不符合要求時就會在方法中返回message 的錯誤提示資訊。restcontroller public class usercontroller 然後在 user 類中新增驗證資訊的要求 public class us...