MethodArgumentNotValidException?和ConstraintViolationException?都是用于處理參數校驗異常的異常類,但它們在不同的上下文中使用。
1. MethodArgumentNotValidException:
? ?- MethodArgumentNotValidException?是在 Spring MVC 或 Spring Boot 中處理參數校驗異常時拋出的異常。繼承至BindException 屬于檢測異常
? ?- 當使用注解(如 @Valid)進行參數校驗時,如果參數違反了約束條件,就會拋出 MethodArgumentNotValidException?異常。
? ?- 通常,該異常是在控制器(Controller)中接收到請求參數后發生的,它包含了關于哪個參數違反了約束條件以及相應的錯誤消息。
? ?- 可通過編寫全局異常處理器 @ExceptionHandler(MethodArgumentNotValidException.class)?來捕獲和處理此異常。
2. ConstraintViolationException:
? ?- ConstraintViolationException?是在 Java Bean Validation(JSR 380)規范中定義的一個異常類。屬于非檢查異常
? ?- 當使用注解進行參數校驗時,如果參數違反了約束條件(例如,@NotNull、@Size、@Pattern等),就會拋出 ConstraintViolationException?異常。
? ?- 該異常不局限于 Spring MVC 或 Spring Boot,可以用于任何遵循 Java Bean Validation 規范的環境。
? ?- 可通過編寫對應的異常處理器來捕獲和處理此異常。
注意:
1.對于參數校驗異常 中MethodArgumentNotValidException?無法捕獲的異常可以用 ConstraintViolationException捕獲處理
2.對于集合參數List<Object>中具體對象的屬性校驗一般情況下MethodArgumentNotValidException捕獲不了,可以用ConstraintViolationException找到是集合參數中中具體哪一個對象參數校驗失敗? 處理代碼舉例
@ResponseBody@ExceptionHandler(value = ConstraintViolationException.class)public Result<xx> doHandException(ConstraintViolationException e) {log.error("服務異常:", e);ConstraintViolationException validException = (ConstraintViolationException) e;Set<ConstraintViolation<?>> violations = validException.getConstraintViolations();// 將驗證失敗的信息轉換為自定義的錯誤信息List<String> errorMessages = new ArrayList<>();for (ConstraintViolation<?> violation : violations) {String errorMessage = violation.getPropertyPath() + ": " + violation.getMessage();errorMessages.add(errorMessage);String str = JSON.toJSONString(violation.getExecutableParameters()[0]);errorMessages.add(str);}log.error(JSON.toJSONString(errorMessages));// 構建錯誤響應return new ResponseEntity<>(Result<xx>.xxx(errorMessages.get(0)), HttpStatus.BAD_REQUEST);}