【问题标题】:How to create custom "Request Body is Missing" error in Spring Boot如何在 Spring Boot 中创建自定义的“Request Body is Missing”错误
【发布时间】:2020-03-14 12:09:48
【问题描述】:

要创建自定义错误,我们需要知道它是什么类型的异常错误。问题是我无法确定“请求正文缺少一个”是哪种错误。起初我以为它被归类为 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。

* 带括号的初审

* 二审 - 不带括号

没有发生错误。

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

【问题讨论】:

  • 你没有使用验证注解吗?这些会为您创建错误响应(并且可以验证所需的参数)。如果您想自定义错误消息,请创建一个扩展 DefaultErrorAttributes 并覆盖 getErrorAttributes 的 @Component。
  • @SledgeHammer 是的,我做到了。但如果我没有放括号,它不会捕获异常。我不明白为什么它只有在我放置支架时才有效,并且如果我移除支架则无法识别丢失的主体。如果我删除了自定义错误消息或删除了 @ControllerAdvise ,则会出现默认消息错误。

标签: java spring exception error-handling


【解决方案1】:

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

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

【讨论】:

  • 谢谢!我会试试这个
猜你喜欢
  • 2017-10-03
  • 2019-03-15
  • 1970-01-01
  • 2016-12-11
  • 2018-02-01
  • 2018-05-28
  • 1970-01-01
  • 2019-04-07
  • 2019-03-01
相关资源
最近更新 更多