@RequestBody
在DTO类属性打上各验证注解后,只需打个@Valid在@RequestBody旁边即可
验证失败抛出:MethodArgumentNotValidException
@RequestParam、@PathVariable
使用这2个注解接受参数时,打@Valid不会起效,而是需要在Controller上打上@Validated
验证失败抛出:ConstraintViolationException
注意:有时会忽略了@RequestBody、@RequestParam在接受参数前,而只打了@Valid
这样验证会生效,验证失败抛出:BindException
记得处理上述抛出的报错
/**
* 请求参数验证错误全局处理
*/
@ControllerAdvice
@ResponseBody
public class ValidExceptionHandler {
/**
* @param e 只打了@Valid在参数前,没有@RequestBody、@RequestParam,验证错误后返回的异常
* @return
*/
@ExceptionHandler(BindException.class)
public ResponseResult bindExceptionHandle(BindException e) {
FieldError fieldError = e.getBindingResult().getFieldError();
return new ResponseResult(null, fieldError.getDefaultMessage());
}
/**
* @param e @RequestParam、@PathVariable,验证错误后返回的异常
* @return
*/
@ExceptionHandler(ConstraintViolationException.class)
public ResponseResult constraintViolationExceptionHandle(ConstraintViolationException e) {
String message = e.getMessage();
return new ResponseResult(null, message);
}
/**
* @param e @RequestBody,验证错误后返回的异常
* @return
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseResult methodArgumentNotValidExceptionHandle(MethodArgumentNotValidException e) {
FieldError fieldError = e.getBindingResult().getFieldError();
return new ResponseResult(null, fieldError.getDefaultMessage());
}
}