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

xj3cbfub  于 2022-10-04  发布在  Java
关注(0)|答案(3)|浏览(191)

所以我有这个接口:

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

}

我不希望错误消息包含类名和路径,而只希望“缺少必需的请求正文”。

我怎么能做到这一点?

谢谢

dwbf0jvd

dwbf0jvd1#

尝试@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/

bqujaahr

bqujaahr2#

试试这个代码

@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

irtuqstp

irtuqstp3#

如果您只需要对这个端点进行更多的控制,那么我建议将请求正文标记为可选,如果为空则签入方法,然后返回您想要显示的任何消息。

@RequestBody(required = false)

相关问题