如何在SpringBoot中使用@Valid时自定义验证失败的响应。

huangapple go评论58阅读模式
英文:

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

  1. 首先,您需要使用 Errors 捕获字段 errors
  2. 然后检查是否 errors.hasErrors()true,然后您可以在 ResponseBody 中发送自定义错误消息。
public ResponseEntity<> sendEmail(@Valid  @RequestBody EmailPostBody emailPostBody, 
                                  Errors errors) {
    if(errors.hasErrors()) {
        new ResponseEntity<>(您的带有错误消息的ResponseBody, http状态码)
    }
}
英文:
  1. First you need to capture the field errors using Errors.
  2. Then check if errors.hasErrors() is true then you can send your custom error message in ResponseBody.
public ResponseEntity<> sendEmail(@Valid  @RequestBody EmailPostBody emailPostBody, 
                                  Errors errors) {
    if(errors.hasErrors()) {
        new ResponseEntity<>(youResponseBodyWithErrorMsg, httpStatusCode)
    }

}

huangapple
  • 本文由 发表于 2020年8月4日 11:01:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/63239623.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定