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

时间:2019-11-19 03:23:38

标签: java spring exception error-handling

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

我为错误创建了控制器建议

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

控制器

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

我使用Postman调用API。

*带括号的首次审判

with bracket

*第二次审判-不带括号

without bracket

未发生错误。

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

0 个答案:

没有答案