英文:
How to customize the response of failed validation when using @Valid in SpringBoot
问题
我正在使用@Valid与@RequestBody一起验证API端点的POST调用请求主体,例如:
当验证失败时,会向调用者返回如下所示的响应:
然而,它只说“验证失败”,但不指示哪个字段有问题。
我想自定义此响应以使其更具体,但不知道如何操作。
有人可以教我吗?
谢谢!
英文:
I am using @Valid together with @RequestBody to validate the request body of post call of an API endpoint, for example:
public ResponseEntity<> sendEmail(@Valid @RequestBody EmailPostBody emailPostBody) {
.
.
.
}
When the validation fails, a response as shown below is returned to the caller.
{
"timestamp": "2020-08-04T02:57:22.839+00:00",
"status": 400,
"error": "Bad Request",
"message": "Validation failed for object='emailPostBody'. Error count: 1",
"path": "/email"
}
However, it only says "Validation failed", but doesn't indicate which field is problematic.
I would like to costumize this response to make it more specific, but don't know how.
Could anyone teach me?
Thanks!
答案1
得分: 5
- 首先,您需要使用
Errors
捕获字段errors
。 - 然后检查是否
errors.hasErrors()
为true
,然后您可以在ResponseBody
中发送自定义错误消息。
public ResponseEntity<> sendEmail(@Valid @RequestBody EmailPostBody emailPostBody,
Errors errors) {
if(errors.hasErrors()) {
new ResponseEntity<>(您的带有错误消息的ResponseBody, http状态码)
}
}
英文:
- First you need to capture the field
errors
usingErrors
. - Then check if
errors.hasErrors()
istrue
then you can send your custom error message inResponseBody
.
public ResponseEntity<> sendEmail(@Valid @RequestBody EmailPostBody emailPostBody,
Errors errors) {
if(errors.hasErrors()) {
new ResponseEntity<>(youResponseBodyWithErrorMsg, httpStatusCode)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论