PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, August 4, 2022

[FIXED] How to get the request body data inside ExceptionHandler class in springboot(REST)

 August 04, 2022     exception, java, request, spring-boot     No comments   

Issue

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.


Solution

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
    }


Answered By - Ferry
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing