public Json page(@Validated @RequestBody QueryVO queryVO, BindingResult result) {
System.out.println("queryVO = " + queryVO);
if (result.hasErrors()) {
result.getFieldErrors().forEach(item->{
System.out.println("item.getField() = " + item.getField());
System.out.println("item.getDefaultMessage() = " + item.getDefaultMessage());
});
}
return Json.succ();
}
这里如果添加了参数BindingResult result
则全局捕获异常不会生效如:
/**
* 处理请求参数格式错误 @RequestBody上使用@Valid 实体上使用@NotNull等,验证失败后抛出的异常是MethodArgumentNotValidException异常
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public Json MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
return Json.fail(message);
}
/**
* 处理Get请求中 使用@Valid 验证路径中请求实体校验失败后抛出的异常
*/
@ExceptionHandler(BindException.class)
public Json BindExceptionHandler(BindException e) {
String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
return Json.fail(message);
}
/**
* 处理请求参数格式错误 @RequestParam上validate失败后抛出的异常是ConstraintViolationException
*/
@ExceptionHandler(ConstraintViolationException.class)
public Json ConstraintViolationExceptionHandler(ConstraintViolationException e) {
String message = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining());
return Json.fail(message);
}