How to get the @RequestBody in an @ExceptionHandler (Spring REST)

前端 未结 3 986
一生所求
一生所求 2020-12-01 14:03

I am using Spring Boot 1.4.1 which includes spring-web-4.3.3. I have a class annotated with @ControllerAdvice and methods annotated with @ExceptionHandle

3条回答
  •  -上瘾入骨i
    2020-12-01 14:36

    Accepted answer creates a new POJO to pass things around, but the same behaviour can be achieved without creating additional objects by reusing the http request.

    Example code for Controller mapping:

    public ResponseEntity savePerson(@RequestBody Person person, WebRequest webRequest) {
        webRequest.setAttribute("person", person, RequestAttributes.SCOPE_REQUEST);
    

    And later in the ExceptionHandler class / method you can use:

    @ExceptionHandler(Exception.class)
    public ResponseEntity exceptionHandling(WebRequest request,Exception thrown) {
    
        Person person = (Person) request.getAttribute("person", RequestAttributes.SCOPE_REQUEST);
    

提交回复
热议问题