1

I'm new to springboot and am working on a legacy project. I'v searched but didn't find answer.

The current working project uses @Valid @RequestBody to validate body, and @ExceptionHandler to catch the exception.

Now the new requirement is dealing with request headers, and I will use the headers(to log for example) regardless of body is valid or not.

The question is I don't konw how to get the headers when @ExceptionHandler hits. Similiar question is How to get the @RequestBody in an @ExceptionHandler (Spring REST) but I cannot figure out how to get headers from injected RequestContext(I even cannot resolve getRequestBody() method in the answer).

The minimal, working and reproducible code is pushed to github.


  • The Model:
public class Book {

  @NotBlank(message = "Title is mandatory")
  public String Title;
}
  • the Controller
@RestController
public class BooksController {

  final Log log = LogFactory.getLog(getClass());

  @PostMapping("/")
  public String add(@RequestHeader("id") String value, @Valid @RequestBody final Book book) {
    log.info(value); // want this value even when hit @ExceptionHandler
    return "added " + book.Title;
  }

  @ResponseStatus(HttpStatus.BAD_REQUEST)
  @ExceptionHandler(value = MethodArgumentNotValidException.class)
  public String handleInvalidRequest(final MethodArgumentNotValidException e) {
    //log headers; ??
    return e.getMessage();
  }

}
  • the Client
curl -H "id:123" -H "Content-Type: application/json" http://localhost:8080 --data '{"Title":""}' 
  • Additonal Information
    jdk 11, springboot 2.5.3, intellij idea 2021.
    model's code is in a library that i cannot change, so the validation logic is unknown to me.

I guess there should be a lot of ways to solve, such as defining some customized middlewares or handles, but I'm not familiar with those and I want to see a solution with least code changes. Thanks!

Lei Yang
  • 3,970
  • 6
  • 38
  • 59

1 Answers1

3

Inside @ExceptionalHandler you can accept HttpServletRequest to get headers

@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public String handleInvalidRequest(final MethodArgumentNotValidException e, final HttpServletRequest req) {
  //log headers; ??
  req.getHeader("My-Header");
  return e.getMessage();
}
Oleh Kurpiak
  • 1,339
  • 14
  • 34