[英]How to customize the response of failed validation when using @Valid in SpringBoot
我正在使用 @Valid 和 @RequestBody 来验证 API 端点的调用后请求正文,例如:
public ResponseEntity<> sendEmail(@Valid @RequestBody EmailPostBody emailPostBody) {
.
.
.
}
当验证失败时,会向调用者返回如下所示的响应。
{
"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"
}
但是,它只显示“验证失败”,但并未指出哪个字段有问题。
我想对此响应进行修饰以使其更具体,但不知道如何。
谁能教我?
谢谢!
Errors
捕获字段errors
。errors.hasErrors()
是否为true
,然后您可以在ResponseBody
中发送自定义错误消息。public ResponseEntity<> sendEmail(@Valid @RequestBody EmailPostBody emailPostBody,
Errors errors) {
if(errors.hasErrors()) {
new ResponseEntity<>(youResponseBodyWithErrorMsg, httpStatusCode)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.