原创:全局异常捕获BindException、MethodArgumentNotValidException和ConstraintViolationException @Validated@Valid

@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 fieldErrors = e.getBindingResult().getFieldErrors();
        List 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 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();
}

 

参考:

https://www.liuyanzhao.com/8000.html

https://blog.csdn.net/u014082714/article/details/107160281/

你可能感兴趣的:(springBoot,全局,异常,BindException,Constraint,Violation)