【发布时间】:2017-03-20 13:48:03
【问题描述】:
我正在使用 Spring MVC 框架编写 REST-API。
我正在使用 bean-validation,例如:
class Person {
@NotNull
String name;
@NotNull
String email;
@Min(0)
Integer age;
}
我在控制器中使用@Valid 注释验证Person:
@PostMapping
public Person create(@Valid @RequestBody Person person) {return ...;}
为了使错误易于阅读,我使用了 Spring 的顶级错误处理程序:
@ControllerAdvice
public class CustomExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody String handle(MethodArgumentNotValidException ex) {
List<String> errors = ex.getBindingResult().getFieldErrors().stream()
.map(this::buildMessage)
.collect(Collectors.toList());
return errors.toString();
}
private String buildMessage(FieldError fe) {
return fe.getField() + " " + fe.getDefaultMessage();
}
}
所以我的错误看起来像:[name may not be null, email may not be null]
现在我需要使用独立于语言的error code,它将被不同的 UI 解析来实现 i18n。
有没有办法构建完整的错误代码?(包含字段名称)
我看到以下解决方案:
-
每次使用注解时都使用自定义消息(丑):
class Person { @NotNull(message="app.error.person.name.not.null") String name; @NotNull(message="app.error.person.email.not.null") String email; @Min(0)(message="app.error.person.age.below.zero") Integer age; } -
在我的异常处理程序中构建正确的代码(不知道如何):
private String buildMessage(FieldError fe) { return "app.error." + fe.getObjectName() + "." + fe.getField() + "." + fe.getDefaultMessage().replaceAll("\\s", "");//don't know how to connect to concrete annotation }所以消息会像
app.error.person.name.maynotbenull 通过删除默认的 ConstraintViolation 并添加自定义(开销),为它们重写所有注释和验证器以构建正确的消息
【问题讨论】:
标签: java spring spring-mvc internationalization bean-validation