Spring 控制器外的异常处理程序

Spring exception handler outside controller

@ControllerAdvice class 中,我有一个 @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 内部进行管理,包括所有异常处理。

恕我直言,您可以尝试两件事:

  • 用拦截器替换过滤器 (*)
  • 在抛出异常的过滤器之前使用另一个过滤器并在那里捕获它(非 Spring MVC 方式,但过滤器 在 [=27= 之外] MVC)

(*) 您仍然无法使用 ExceptionHandler,因为异常将被抛出到控制器之外,但您可以使用 HandlerExceptionResolver。