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);}