簡體   English   中英

Java/Spring:覆蓋默認的@RequestBody 功能

[英]Java/Spring: Override default @RequestBody functionality

所以我有這個 API:

public Map<String, Object> myFunc(@RequestBody @Valid MyPrivateEntity body) {}

其中標有@RequestBody 和@Valid

問題是,如果我在調用此 API 時省略正文,則會收到以下錯誤消息:

{
"title": "Failed to parse request",
"detail": "Required request body is missing: public com.privatePackage.misc.service.rest.MyPrivateEntity com.privatePackage.misc.service.rest.MyPrivateResource.myFunc(java.lang.String, com.privatePackage.misc.service.rest.MyPrivateEntity)",
"status": 400

}

我不希望錯誤消息包含 class 名稱和路徑,而只是“缺少必需的請求正文”。

我怎樣才能做到這一點?

謝謝

試試這個代碼

@ExceptionHandler(BindException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)  // return 400 if validate fail
public String handleBindException(BindException e) {
    // return message of first error
    String errorMessage = "Request not found";
    if (e.getBindingResult().hasErrors())
        e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
    return errorMessage;
}

或者使用這種方式

public Map<String, Object> myFunc(
        @RequestBody @Valid MyPrivateEntity body,
        BindingResult bindingResult) {  // add this parameter
    // When there is a BindingResult, the error is temporarily ignored for manual handling
    // If there is an error, block it
    if (bindingResult.hasErrors())
        throw new Exception("...");

}

參考: https://www.baeldung.com/spring-boot-bean-validation

如果您只需要對此端點進行更多控制,那么我建議將請求正文標記為可選,並檢查該方法是否為 null 然后返回您想要顯示的任何消息。

@RequestBody(required = false)

嘗試使用@ControllerAdvice來自定義您的消息。

@ControllerAdvice
        public class RestExceptionHandler extends ResponseEntityExceptionHandler {
    
            @Override
            protected ResponseEntity<Object> handleHttpMessageNotReadable(
                HttpMessageNotReadableException ex, HttpHeaders headers,
                HttpStatus status, WebRequest request) {
                // paste custom hadling here
            }
        }

參考:

https://ittutorialpoint.com/spring-rest-handling-empty-request-body-400-bad-request/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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