Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring exception handler outside controller

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?

like image 512
Kaushik Avatar asked May 02 '15 08:05

Kaushik


People also ask

How does Spring controller handle exceptions?

Spring MVC provides exception handling for your web application to make sure you are sending your own exception page instead of the server-generated exception to the user. The @ExceptionHandler annotation is used to detect certain runtime exceptions and send responses according to the exception.

How do you handle exception globally in spring boot?

In Java, exception handling is done by try, catch blocks but spring boot also allows us to provide customized global exception handling where we need not to add try catch block everwhere, we can create a separate class for handling exceptions and it also separates the exception handling code from businesss logic code.

What is the difference between ControllerAdvice and RestControllerAdvice?

The differences between @RestControllerAdvice and @ControllerAdvice is : @RestControllerAdvice = @ControllerAdvice + @ResponseBody . - we can use in REST web services. @ControllerAdvice - We can use in both MVC and Rest web services, need to provide the ResponseBody if we use this in Rest web services.

What is ControllerAdvice in spring?

@ControllerAdvice is a specialization of the @Component annotation which allows to handle exceptions across the whole application in one global handling component. It can be viewed as an interceptor of exceptions thrown by methods annotated with @RequestMapping and similar.


1 Answers

I'm afraid you cannot. Here is (broadly) how à request is processed in a Spring MVC web application :

servlet container
    filters before FilterChain.doFilter
        DispatcherServlet  => here is all Spring MVC machinery
    filters after FilterChain.doFilter
servlet container

All Spring MVC machinery is managed inside the DispatcherServlet, including all exception handling.

IMHO, you can try two things :

  • replace the filter with an interceptor (*)
  • use another filter coming before the one where exception is thrown and catch it there (the non Spring MVC way, but filters are outside of Spring MVC)

(*) You will still not be able to use an ExceptionHandler since exception will be thrown outside of a controller, but you could use a HandlerExceptionResolver.

like image 149
Serge Ballesta Avatar answered Sep 22 '22 11:09

Serge Ballesta