在@ControllerAdvice
类中,我有一个@ExceptionHandler
,该处理程序可以很好地处理控制器错误,但是如果我有过滤器,它们将无法处理异常。如何处理这些异常?
过滤器为:-
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);
}
...
}
异常处理程序是(在@ControllerAdvice中)
@ExceptionHandler(APIException.class)
public ResponseEntity<ErrorDTO> handleAPIException(APIException e) {
return new ResponseEntity<ErrorDTO>(new ErrorDTO(e.getMessage()),
e.getHttpStatus());
}
更新
我的要求是为Spring安全性过滤器提供一个全局异常处理程序。有什么办法吗?
最佳答案
恐怕你不能。这是(广泛地)在Spring MVC Web应用程序中处理à请求的方式:
servlet container
filters before FilterChain.doFilter
DispatcherServlet => here is all Spring MVC machinery
filters after FilterChain.doFilter
servlet container
所有Spring MVC机械都在DispatcherServlet内部进行管理,包括所有异常处理。
恕我直言,您可以尝试两件事:
(*)您将仍然无法使用ExceptionHandler,因为异常将被抛出到控制器之外,但是您可以使用HandlerExceptionResolver。