要创建自定义错误,我们需要知道它是哪种异常错误。问题是我无法确定“请求正文缺失”是哪种错误。起初我以为它被归类为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。
*带括号的首次审判
*第二次审判-不带括号
未发生错误。
我的问题是,当请求中根本没有附加请求正文时,如何处理此错误。在这种情况下,我也想返回“无效参数”错误。