繁体   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