I have a class annotated with @ControllerAdvice and methods annotated with @ExceptionHandler to handle exceptions thrown by the service code. When handling these exceptions, I would like to get the @RequestBody that was part of the request POST operations.
I tried by creating POJO class for the request sent and tried to retrieve inside exception handler class but it returns null.
Followed the same solution given in this query~ How to get the @RequestBody in an @ExceptionHandler (Spring REST)
It doesn't work.
I also tried with httpServertRequest, even that return null for the request data.
I want to get the request body of the api inside ExceptionHandler method. Based on the request body data I have to return the error response.
I also want the query param data to be used inside ExceptionHandler method.
Please provide with a solution. Thank you.
CodePudding user response:
The Stream of Request Body only read once, so you can't retrieve it for the second time inside ControllerAdvice, thus cache the request body with ContentCachingRequestWrapper first. Create a new Spring component like this:
@Component
public class FilterConfig extends GenericFilterBean{
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException{
HttpServletRequest request = (HttpServletRequest) servletRequest;
ContentCachingRequestWrapper wrapper = new ContentCachingRequestWrapper(request);
filterChain.doFilter(wrapper, servletResponse);
}
}
then in @ControllerAdvice make your @ExceptionHandler accept ContentCachingRequestWrapper as parameter.
@ExceptionHandler(Exception.class)
public ResponseEntity<Object> handleDefaultException(Exception ex, ContentCachingRequestWrapper request){
String reqBody = "your request body is " new String(request.getContentAsByteArray(), StandardCharsets.UTF_8);
// then do another thing you wanted for exception handling
}