如何使用Spring Boot + Data Rest来解析基于Accept-Language的验证消息?

时间:2015-01-28 11:19:31

标签: spring spring-boot bean-validation hibernate-validator spring-data-rest

我有一个基于Spring Boot(1.2.0.RC2)和Spring Data Rest的API应用程序,使用Hibernate bean验证(开箱即用)。

为了向API客户端公开无效输入(400 Bad Request),我创建了一个用@ControllerAdvice注释的异常处理程序类,它具有以下方法:

@ExceptionHandler
@ResponseBody ResponseEntity handleViolation(ConstraintViolationException exception) {
ErrorRepresentation.Builder builder = new ErrorRepresentation.Builder()    
    .withViolations(
        exception.getConstraintViolations().stream()
            .map(v -> {
                ErrorRepresentation.Builder violationBuilder = new ErrorRepresentation.Builder();
                violationBuilder.withDetail(v.getMessage());
                violationBuilder.withInternalRef(v.getPropertyPath().iterator().next().getName());
                return violationBuilder;
            })
            .map(ErrorRepresentation.Builder::build)
            .collect(Collectors.toList()));

    builder.withStatus(HttpStatus.BAD_REQUEST.value());
    ErrorRepresentation error = builder.build();    
    return createResponseEntity(error);
}

这里我将javax.validation.ConstraintViolation映射到我自己的自定义错误表示类中,然后将其序列化为JSON。到目前为止一切都很好!

i18n正在运行,但仅基于服务器环境的默认语言环境。

我希望Spring能够自动引导消息插值,以便在消息插值发生之前,每次请求都会选择Accept-Language并更改Locale

关于如何将它们放在一起的任何提示?

0 个答案:

没有答案