0

In a Spring Boot API Rest app I have a ExceptionHandler for a given RestController. This controller has a @RequestBody anotation that is a String in one of its methods.

@RestController
public class FooController {
    @PostMapping("/my_url")
    public ResponseEntity myMethod(@RequestBody String param) { 
        ....
    }

    @ExceptionHandler({MyCustomException.class})
    public ResponseEntity handleMyCustomException(MyCustomException ex) {
        ...
    }

}

I'm not able to access the aforementioned String in the @ExceptionHandler method (that corresponds to the body of the POST petition as the title says)

I can set the param variable in the WebRequest and then retrieve it the handle method but this seems a very hacky way to achieve it.

Is there a solution provided by the framework to access the body of the POST petition in a ExceptionHandler?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Jorge Lavín
  • 937
  • 8
  • 22

2 Answers2

2

I think the question you are asking is the same as this one. Unfortunately, there does not seem to have an elegant and easy solution.

Since you are throwing a custom exception, may be you could consider adding an attribute in the exception to hold that extra information (i.e. param).

HL'REB
  • 838
  • 11
  • 17
0

Is that you are looking for?

@ControllerAdvice
public class MyExceptionHandler extends ResponseEntityExceptionHandler {

/**Here you can inject any you spring beans**/

  @ExceptionHandler({ MyCustomException.class })
  protected ResponseEntity<Object> handleInvalidRequest(RuntimeException exc, WebRequest request) {
    MyCustomException exception = (MyCustomException) exc;
    /**here you can do watewer you want with an exception and a body**/
    HttpHeaders headers = new HttpHeaders();
    /**here you have to create some response objects if needed**/
    YourExceptionWrapper error = new YourExceptionWrapper(exception.getMessage());
    headers.setContentType(MediaType.APPLICATION_JSON);
    /**and then send a bad request to a front-end**/
    return handleExceptionInternal(exc, error, headers, HttpStatus.BAD_REQUEST, request);
  }
}
Yuriy Tsarkov
  • 2,461
  • 2
  • 14
  • 28