Springboot Validate verifies pits encountered in unified exception handling

最近在使用validation完成数据后端校验,遇到一个很奇葩的问题,特此做一个记录。

The regular validation configuration is not written, and the pits encountered are written.

坑一:
@RestControllerAdvice
@Component
public class GlobalExceptionHandler {
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String handle(ValidationException exception) {
        List<String> errorMsg = new ArrayList<>();
        if (exception instanceof ConstraintViolationException) {
            ConstraintViolationException exs = (ConstraintViolationException) exception;

            Set<ConstraintViolation<?>> violations = exs.getConstraintViolations();
            for (ConstraintViolation<?> item : violations) {
                /**打印验证不通过的信息*/
                System.out.println(item.getMessage());
                errorMsg.add(item.getMessage());
            }
        }
        return "bad request, " + JSON.toJSONString(errorMsg);
    }
}

Do a unified exception return, the result is that the processing method requires adding the @Validated annotation to the controller, and only the @Valid tag can be added to the corresponding method

  @ApiOperation("新增用户")
   @PostMapping("saveUser")
    public String saveUser(@RequestBody @Valid User user , BindResult rsult) {
        User newUser = userService.insert(user);
        return JSONObject.toJSONString(newUser, SerializerFeature.WriteMapNullValue);
    }

Otherwise, there will be a problem that the returned information cannot be validated or formatted.

坑二:
@RestControllerAdvice
@Component
public class GlobalExceptionHandler {

    @ExceptionHandler(BindException.class)
    public String handle(BindException ex) {
        List<FieldError> fieldError = ex.getBindingResult().getFieldErrors();
        System.out.println(fieldError);
        StringBuilder sb = new StringBuilder();
        return sb.toString();
    }
}

There is a return error in the front end of this method, but the BindException has been unable to be obtained.

解决方法:获取 MethodArgumentNotValidException异常,该方法下也有一个BindingResult属性
@RestControllerAdvice
@Component
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public String exception(MethodArgumentNotValidException exception) {
        BindingResult result = exception.getBindingResult();
        final List<FieldError> fieldErrors = result.getFieldErrors();
        List<String> errorMsg = new ArrayList<>();

        for (FieldError error : fieldErrors) {
           errorMsg.add(error.getDefaultMessage());
        }
        return JSONObject.toJSONString(errorMsg);
    }
}
{{o.name}}
{{m.name}}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324187164&siteId=291194637