Home > Enterprise >  Spring-Boot:How to get all request body in WebRequest
Spring-Boot:How to get all request body in WebRequest

Time:10-18

Is it possible to fetch RequestBody from WebRequest object? I am handling exceptions from controller advice so would like to handle the request as well to send data back in response. I saw its documentation what I understood is we can fetch query params from that object for GET request. If there is any other approach which I missed can somebody please help.

@NonNull
@Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(
  @Nullable HttpMessageNotReadableException ex,
  @Nullable HttpHeaders headers,
  HttpStatus status,
  @Nullable WebRequest request) {
 //handling of input request we got from Spring Controller
}

CodePudding user response:

Try passing InputStream / Reader for access to the request's content. This will be the raw InputStream/Reader as exposed by the Servlet API. and/or response objects (typically from the Servlet API) as per official documentation.

@NonNull
@Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(
  @Nullable HttpMessageNotReadableException ex,
  @Nullable HttpHeaders headers,
  HttpStatus status,
  @Nullable WebRequest request,
  InputStream requestContent
) {
 //handling of input request we got from Spring Controller
}

CodePudding user response:

When exception occurs in your controller - catch it and extract any and all info you want. Create your own class - Lets say CustomErrorInfo and fill it with all the info you want and throw your own custom exception that will contain your CustomErrorInfo class and the original exception. Than in your controller advice add method that would handle your custom exception and there you will have an access to your CustomErrorInfo class instance thast you filled when exception occurred

  • Related