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

Kau*_*hik 5 java spring spring-security

@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);
    }

    ...
}
Run Code Online (Sandbox Code Playgroud)

异常处理程序是(在@ControllerAdvice 中)

    @ExceptionHandler(APIException.class)
    public ResponseEntity<ErrorDTO> handleAPIException(APIException e) {
        return new ResponseEntity<ErrorDTO>(new ErrorDTO(e.getMessage()),
                e.getHttpStatus());
    }
Run Code Online (Sandbox Code Playgroud)

更新

我的要求是为 spring 安全过滤器提供一个全局异常处理程序。有什么办法吗?

Ser*_*sta 5

恐怕你不能。这是(大致上)在 Spring MVC Web 应用程序中处理请求的方式:

servlet container
    filters before FilterChain.doFilter
        DispatcherServlet  => here is all Spring MVC machinery
    filters after FilterChain.doFilter
servlet container
Run Code Online (Sandbox Code Playgroud)

所有 Spring MVC 机制都在 DispatcherServlet 内进行管理,包括所有异常处理。

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

  • 用拦截器 (*) 替换过滤器
  • 用另一种过滤器,其中异常被抛出一个之前来了,抓住它有(非Spring MVC的方式,但过滤器Spring MVC的外面)

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