繁体   English   中英

如何在 Spring 引导中创建自定义“缺少请求正文”错误

[英]How to create custom "Request Body is Missing" error in Spring Boot

要创建自定义错误,我们需要知道它是什么类型的异常错误。 问题是我无法确定“请求正文缺少一个”是哪种错误。 起初我以为它被归类为MethodArgumentNotValidException ,但它没有捕捉到错误。

我为错误创建 Controller 建议

@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException exception, HttpHeaders headers, HttpStatus status, WebRequest request){
        MyObject<Object> error = MyObject.failure("Invalid Parameter");
        log.error("argument invalid", exception);
        return new ResponseEntity<Object>(error, new HttpHeaders(), HttpStatus.OK);
}

controller

@PostMapping(value = "/tes")
public MyObject<MyRes> myTest(@Valid @RequestBody MyReq req, HttpServletRequest hsReq) throws Exception{
        return myService.updateTestData(req);
}

我用 Postman 来调用 API。

* 带支架的初试

带支架

* 二审 - 不带支架

不带支架

没有发生错误。

我的问题是,当请求中根本没有附加请求正文时,如何处理此错误。 在这种情况下,我也想返回“无效参数”错误。

这可能会迟到,但您可能想尝试在 ControllerAdvice class 上添加它,这就是我在尝试发送空请求时发现Required request body is missing错误的方式。

@ExceptionHandler(HttpMessageNotReadableException.class)
public ResponseEntity<Object> handleMissingRequestBody(HttpMessageNotReadableException ex) {
    return new ResponseEntity<Object>(ex.getMessage(), HttpStatus.BAD_REQUEST);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM