@ModelAttribute方法处理@RequestBody对象抛出HttpMessageNotReadableException

时间:2017-10-09 03:52:53

标签: java spring-boot exception-handling modelattribute

在@ControllerAdvice类中,我只想获取请求体。我不知道在@ModelAttribute方法中处理它并将@RequestBody值设置为props更好。所以,这里的问题是当我打开@RequestBody它仍然按预期得到请求体,但之后它会抛出HttpMessageNotReadableException。 有人可以告诉我原因,并有想法解决问题。这对我来说真的很重要。

@ControllerAdvice 
public class CustomRestExceptionHandler extends ResponseEntityExceptionHandler 
{


    public CustomRestExceptionHandler() {
        super();
    }

    private Object request;

    @ModelAttribute
    public void setRequest(@RequestBody Object request) {
        this.request = request;
    }

    @Override protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        logger.info(this.request)
    }

    @Override
    protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        return new ResponseEntity<Object>(ex, HttpStatus.BAD_REQUEST);
    }

}

1 个答案:

答案 0 :(得分:1)

我相信您收到 HttpMessageNotReadableException 的原因是您尝试使用 @RequestBody 注释两次将 JSON 映射到对象。首先在 ControllerAdvice 模型属性中,然后在控制器方法参数中。假设你有一个看起来像这样的控制器

@RestController
public class MyController{

@PostMapping("endpoint")
public Response processRequest(@RequestBody MyObject myRequest)
System.out.println("bla bla");
}

尝试删除@RequestBody注解并将其更改为

@PostMapping("endpoint")
public Response processRequest(final MyObject myRequest)
System.out.println("bla bla");
}

然后将您的 Controller Advice 修改为如下所示:

@ControllerAdvice 
public class CustomRestExceptionHandler extends ResponseEntityExceptionHandler 
{


    public CustomRestExceptionHandler() {
        super();
    }

    private MyObject request;



@ModelAttribute("myRequest") //same as in controller
    public MyObject setRequest(@RequestBody MyObject request) {
        this.request = request;
        return request;
    }

    @Override protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        logger.info(this.request)
    }

    @Override
    protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        return new ResponseEntity<Object>(ex, HttpStatus.BAD_REQUEST);
    }

}

您的 ModelAttribute 现在返回转换后的对象,以便将其传递给控制器​​。希望它能解决您的问题。