0

Why can't global exception handling handle exceptions thrown in the filter?

My code is looking like this at the moment:

  1. Filter method

     @Override
     public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
         HttpServletRequest   httpServletRequest = (HttpServletRequest) servletRequest;
         String token = httpServletRequest.getHeader("token");
         if (token==null)
             throw new NoTokenException();
    
         try {
             String s = jwtToken.parseJwt(token);
             httpServletRequest.setAttribute("id",s);
         }catch (Exception e){
             throw new RuntimeException();
         }
    
         filterChain.doFilter(servletRequest,servletResponse);
     }
    
  2. Controller advice class

     @RestControllerAdvice
     public class GlobalExceptionHandle {
    
         @ExceptionHandler(Exception.class)
         public void Handle(Exception e, HttpServletResponse response) throws IOException {
             response.setContentType("application/json;charset=UTF-8");
             response.getWriter().write("msg");
             response.flushBuffer();
         }
     }
    
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614

1 Answers1

0

@RestControllerAdvice does not work for filters. For them, you need to implement an additional filter as depicted in https://stackoverflow.com/a/34633687/16572295.

João Dias
  • 16,277
  • 6
  • 33
  • 45