簡體   English   中英

SpringBoot中使用@Valid時如何自定義驗證失敗的響應

[英]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"
}

但是,它只顯示“驗證失敗”,但並未指出哪個字段有問題。

我想對此響應進行修飾以使其更具體,但不知道如何。

誰能教我?

謝謝!

  1. 首先,您需要使用Errors捕獲字段errors
  2. 然后檢查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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM