简体   繁体   English

Java/Spring:覆盖默认的@RequestBody 功能

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

So I have this API:所以我有这个 API:

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

Which is marked with @RequestBody and @Valid其中标有@RequestBody 和@Valid

The thing is, if I omit the body when calling this API, I get the following error message:问题是,如果我在调用此 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

} }

I don't want the error message to include class names and paths, instead just "Required request body is missing".我不希望错误消息包含 class 名称和路径,而只是“缺少必需的请求正文”。

How can I do that?我怎样才能做到这一点?

Thanks谢谢

Try this code试试这个代码

@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;
}

Or use this way或者使用这种方式

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("...");

}

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

If you need more control on only this endpoint then I'll suggest to mark request body optional and check in the method if it's null then return whatever message you want to show.如果您只需要对此端点进行更多控制,那么我建议将请求正文标记为可选,并检查该方法是否为 null 然后返回您想要显示的任何消息。

@RequestBody(required = false)

Try @ControllerAdvice to customise your message.尝试使用@ControllerAdvice来自定义您的消息。

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

Reference:参考:

https://ittutorialpoint.com/spring-rest-handling-empty-request-body-400-bad-request/ 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