java - "Validation failed for object=' 用户 '. Error count: 1"而不是 "email must not be null"

标签 java spring hibernate rest validation

我有一个验证和创建用户的 api。当我不在请求正文中输入电子邮件时,我会收到

{
    "timestamp": "2020-11-26T13:55:40.116+00:00",
    "status": 400,
    "error": "Bad Request",
    "message": "Validation failed for object='user'. Error count: 1",
    "path": "/api/users"
}
我想将消息更改为更不稳定的错误,例如“电子邮件不能为空”。
这就是我模型的属性的样子:
@NotNull
private String email;
这是我的 Controller 的方法:
@PostMapping("/users")
public ResponseEntity<User> addUser(@RequestBody @Valid User user) {
    User savedUser = manager.save(user);
    URI uri = ServletUriComponentsBuilder.fromCurrentRequest()
            .path("/{id}")
            .buildAndExpand(savedUser.getId())
            .toUri();
    return ResponseEntity.ok(savedUser);
}
我尝试在 @NotNull 中设置自定义消息注释,但消息不会改变。此外,当错误被抛出时,控制台会显示此消息:
2020-11-26 15:09:11.460  WARN 7137 --- [nio-8080-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MethodArgumentNotValidException: Validation failed for argument [0] in public org.springframework.http.ResponseEntity<pl.vemu.socialApp.entities.User> pl.vemu.socialApp.controllers.UserController.addUser(pl.vemu.socialApp.entities.User) throws pl.vemu.socialApp.exceptions.user.UserWithEmailAlreadyExistException: [Field error in object 'user' on field 'email': rejected value [xsars.pl]; codes [Email.user.email,Email.email,Email.java.lang.String,Email]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.email,email]; arguments []; default message [email],[Ljavax.validation.constraints.Pattern$Flag;@2a50b33,.*]; default message [must be a well-formed email address]] ]
如何在响应json中设置消息?
如何在控制台中摆脱此消息?其他错误不会在控制台中显示消息。

最佳答案

问题是 Spring 默认情况下在绑定(bind)时不会发送错误。要启用它,您必须添加 server.error.include-binding-errors=always在您的 application.properties 中。

关于java - "Validation failed for object=' 用户 '. Error count: 1"而不是 "email must not be null",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65023750/

相关文章:

java - 当事务仍处于 Activity 状态时无法关闭连接 connection.close() 上出现异常

java - HibernateInterceptor和proxyTargetClass有什么用

java - 使用查询字符串从 HTTP 端点下载 PNG 文件

java - 如何使用java发送电子邮件

Spring Data JPA 将原生查询结果映射到非实体 POJO

java - 使用 requiresUnpack 使用 Maven 构建的 Spring Boot JAR 不起作用

java - Spring - 响应文件流的正确方法是什么?

java - Data Nucleus 带有注释的多对多属性关系

java - 如何防止使用 Kafka 连接接收器插入 Kafka 消息中不需要的属性?

java - 从网站获取 XML?