gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 01:10:24 31 4
gpt4 key购买 nike

我有一个验证和创建用户的 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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com