原创:全局异常捕获BindException、MethodArgumentNotValidException和ConstraintViolationException @Validated@Valid
BindException(@Validated @Valid):@ResponseStatus(HttpStatus.BAD_REQUEST)@ExceptionHandler(BindException.class)public ResultVO bindExceptionHandler(BindException e) {List<FieldError> fieldErrors
·
@Validated @Valid
@NotBlank——String
@NotNull——Integer
@NotEmpty——Collecion
一般entity的参数校验,异常就这如下三种:
BindException(@Validated @Valid仅对于表单提交有效,对于以json格式提交将会失效):
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(BindException.class)
public ResultVO bindExceptionHandler(BindException e) {
List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
List<String> msgList = fieldErrors.stream()
.map(o -> o.getDefaultMessage())
.collect(Collectors.toList());
String messages = StringUtils.join(msgList.toArray(), ";");
log.error("Validation格式校验异常:-------------->{}",messages);
return ResultVO.builder().errorcode(HttpStatus.BAD_REQUEST.value()).errormessage(messages).build();
}
MethodArgumentNotValidException(@Validated @Valid 前端提交的方式为json格式有效,出现异常时会被该异常类处理):
/**
* @Validated 校验错误异常处理
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public ResultVO handler(MethodArgumentNotValidException e) throws IOException {
BindingResult bindingResult = e.getBindingResult();
ObjectError objectError = bindingResult.getAllErrors().stream().findFirst().get();
String messages = objectError.getDefaultMessage();
log.error("MethodArgumentNotValidException异常:-------------->{}", messages);
return ResultVO.builder().errorcode(400).errormessage(messages).build();
}
ConstraintViolationException(@NotBlank @NotNull @NotEmpty):
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = ConstraintViolationException.class)
public ResultVO handler(ConstraintViolationException e) throws IOException {
List<String> msgList = new ArrayList<>();
for (ConstraintViolation<?> constraintViolation : e.getConstraintViolations()) {
msgList.add(constraintViolation.getMessage());
}
String messages = StringUtils.join(msgList.toArray(), ";");
log.error("entity格式校验异常:-------------->{}",messages);
return ResultVO.builder().errorcode(400).errormessage(messages).build();
}
参考:
更多推荐
所有评论(0)