Intercept @RequestHeader exception for missing header
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.
You can also achieve this by use of annotation @ControllerAdvice
from spring.
@ControllerAdvice
public class ExceptionHandler extends ResponseEntityExceptionHandler{
/**
* Handle ServletRequestBindingException. Triggered when a 'required' request
* header parameter is missing.
*
* @param ex ServletRequestBindingException
* @param headers HttpHeaders
* @param status HttpStatus
* @param request WebRequest
* @return the ResponseEntity object
*/
@Override
protected ResponseEntity<Object> handleServletRequestBindingException(ServletRequestBindingException ex,
HttpHeaders headers, HttpStatus status, WebRequest request) {
return new ResponseEntity<>(ex.getMessage(), headers, status);
}
}
The response when you access your API without the required request header is:
Missing request header 'Authorization' for method parameter of type String
Like this exception, you can customise all other exceptions.