In @ControllerAdvice class I have an @ExceptionHandler, this handler works well with controller errors but if I have a filter they can't handle the exception. How can I handle these exceptions?
The filter is:-
public class AuthFilter extends UsernamePasswordAuthenticationFilter {
private LoginDTO loginDTO;
public AuthFilter() {
setRequiresAuthenticationRequestMatcher(
new AntPathRequestMatcher("/login", "POST"));
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response) throws AuthenticationException {
try {
loginDTO = new ObjectMapper().readValue(request.getReader(), LoginDTO.class);
} catch (Exception e) {
throw new APIException(ExceptionMessages.INVALID_LOGIN_JSON,
HttpStatus.BAD_REQUEST);
}
return super.attemptAuthentication(request, response);
}
...
}
The exception handler is (in @ControllerAdvice)
@ExceptionHandler(APIException.class)
public ResponseEntity<ErrorDTO> handleAPIException(APIException e) {
return new ResponseEntity<ErrorDTO>(new ErrorDTO(e.getMessage()),
e.getHttpStatus());
}
UPDATE
My requirement is having a global exception handler for spring security filters. Is there any way to do it?
@ExceptionHandleras those are only for controllers and execute within theDispatcherServletfilters execute before filters so no way an@ExceptionHandler(without moving it to another filter, basically duplicating the dispatcherservlet to a filter) can handle this (nor should it imho). Also you are aware that your custom filter is flawed? - M. DeinumloginDTOnow what do you think what happens when 10 requests come in.... - M. DeinumExceptionHandlingFilter. But what is your use case, why are you doing this? - M. Deinum