Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercept @RequestHeader exception for missing header

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?

like image 788
Ruslan Islamov Avatar asked Aug 06 '14 02:08

Ruslan Islamov


People also ask

How do you deal with MissingRequestHeaderException?

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 do you validate headers in spring boot?

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.

What is @RequestHeader in spring boot?

@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.

Can a request header null?

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.


1 Answers

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.

like image 164
Mikayil Abdullayev Avatar answered Sep 18 '22 02:09

Mikayil Abdullayev