I have a method in controller with has parameter for example
@RequestMapping(value = "/{blabla}", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public void post(@RequestHeader("ETag") int etag)
If there is no ETag header in request - client gets 400 (BAD_REQUEST), which is not any informative. I need to somehow handle this exception and send my own exception to client (I use JSON for this purpose). I know that I can intercept exception via @ExceptionHandler, but in that case all HTTP 400 requests will be handled, but I want that have missing ETag in headers. Any ideas?
One of the method is handleServletRequestBindingException. So your MissingRequestHeaderException is handled by the method of ResponseEntityExceptionHandler. If you have to verify, go to the code of ResponseEntityExceptionHandler in your IDE. Hope this helps.
How to Read Optional Request Header in Spring Boot. The optional request header can be read using @RequestHeader annotation. Add required parameter in the annotation and set as false. If the optional request header is available, the value is printed.
@RequestHeader annotation binds request header values to method parameters. If the method parameter is Map<String, String> , MultiValueMap<String, String> , or HttpHeaders then the map is populated with all header names and values.
The use of a NULL (0 valued) character within the name or value of an HTTP request Header field is banned by the standard. An attacker embeds NULL characters within the Header field in order to evade detection mechanisms.
In case Spring version is 5+ then the exact exception you need to handle is the MissingRequestHeaderException
. If your global exception handler class extends ResponseEntityExceptionHandler
then adding an @ExceptionHandler
for ServletRequestBindingException
won't work because MissingRequestHeaderException
extends ServletRequestBindingException
and the latter is handled inside the handleException
method of the ResponseEntityExceptionHandler
. If you try you're going to get Ambiguous @ExceptionHandler method mapped for ...
exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With