Get request values from ExceptionHandler using Spring MVC

前端 未结 1 374
深忆病人
深忆病人 2021-01-19 23:34

I have a Spring MVC Controller and an Exception Handler. When an exception occurs, I want the Exception Handler to log all the GET/POST data that was sent in the request. Ho

1条回答
  •  一整个雨季
    2021-01-20 00:07

    Well the request body is in the HttpServletRequest.

    You could access the RAW request body by doing something like:

    String body = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
    

    from the exception handler method. (using java 8).

    Then you can parse the body string as a POJO.

    EDIT

    It's been noted that the avobe answer does not work. This happens because when the body is parsed (with @RequestBody) the http connection stream is closed, hence the request body cannot be accessed again. Howver you could inject a property directly to the httpRequest from your controller method and then access the value in your Exception handler:

    @RestController
    @RequestMapping(ApiVersion.V1.prefix)
    public class BatchController {
        @PostMapping("/batch")
        public @ResponseBody BatchResponse runBatch(@RequestBody BatchRequest batchRequest, HttpServletRequest request) throws IOException {
            System.out.println(batchRequest.getName());
            request.setAttribute("batchRequest" , batchRequest);
            throw new IllegalArgumentException("Some error");
        }
    
        @ExceptionHandler(IllegalArgumentException.class)
        public @ResponseBody BatchResponse handle(HttpServletRequest request) {
            BatchRequest batchRequest = (BatchRequest) request.getAttribute("batchRequest");
            System.out.println("handling exception");
            return new BatchResponse(batchRequest.getName());
        }
    }
    

    Hope this helps

    0 讨论(0)
提交回复
热议问题