首页 > 解决方案 > Spring Boot 休息请求数据类型验证

问题描述

我正在对 Spring Boot Rest 中的请求对象进行验证。我必须验证请求的数据类型。该请求具有多个布尔值,并尝试验证是否为布尔数据类型传递了字符串。我在我的 ControllerAdvice 类中处理了 HttpMessageNotReadableException 并发送了错误消息列表。但在我的回应中,只有第一个字段抛出异常。如果有线索,请帮忙。

标签: spring-boot

解决方案


@Vishnu Dubey 使用这个.....

  @RestControllerAdvice
        public class ServiceControllerAdvice {
            private static final Logger log = LoggerFactory.getLogger(ServiceControllerAdvice.class);
            @ExceptionHandler(value = { ConstraintViolationException.class })
            @ResponseStatus(value = HttpStatus.BAD_REQUEST)
            public ServiceResponse<?> constraintViolationException(final ConstraintViolationException ex) {
                log.error("Validation failed", ex);
                final ServiceResponse<?> response = new ServiceResponse<>(-1);
                final Error error = new Error();
                error.setCode("PS01");
                error.setContext(ex);
                error.setMessage(ex.getMessage());
                response.setError(error);
                return response;
            }
}

推荐阅读