0

I have a Spring Boot Java application. There is a service class that throws a "401 Unauthorized" HttpClientErrorException since the access token used in the application has expired. I want to handle this exception globally for which I have used the @ControllerAdvice annotation. The error is:

Caused by: org.springframework.web.client.HttpClientErrorException: 401 Unauthorized

The class is:

@Slf4j
@EnableWebMvc
@ControllerAdvice(basePackages = Service.class)
public class HttpClientErrorHandler{
    @ExceptionHandler(HttpClientErrorException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public String errorHandle(HttpClientErrorException e) {
        log.error("log HttpClientErrorException: ", e);
    return "HttpClientErrorException_message";
   }
}

Since the exception was caused in the service class, I have mentioned it specifically in the basePackages. The entire configuration for the program is specified in the application.yml file. I have not used the xml configuration. I don't understand why the @ControllerAdvice annotation is not working. The program still throws the exception. Can someone explain?

nehacharya
  • 925
  • 1
  • 11
  • 31

2 Answers2

0

@ControllerAdvice(basePackages = Service.class)

The exception is bubbled to @Controller class, and @ControllerAdvice is supposed to apply to controller, so you should set basePackageClasses to your controller package instead of your service package.

By default, @ControllerAdvice is applied to all Controller so you can remove the basePackageClasses unless you want to narrow down the controller advise

Mạnh Quyết Nguyễn
  • 17,677
  • 1
  • 23
  • 51
  • Yes I understood what you are trying to say and made the required changes as suggested by you but it's still not handling the exception. :( – nehacharya May 14 '18 at 12:03
0

I had also faced similar issue,

try adding @Order(Ordered.HIGHEST_PRECEDENCE) below @ControllerAdvice.

We add it to get priority over Spring's default DefaultHandlerExceptionResolver. To understand more about why we add it read this answer. Also no need to give base packages, it will consider all packages by default.

To handle exception of any other type you can include below existing exception handler for HttpClientErrorException you already have written,

@ExceptionHandler(Exception.class)
public Strring handleAnyExceptions(Exception ex) {
    return "your message";
} 

Hope it helps !

rdj7
  • 1,905
  • 4
  • 18
  • 33
  • I tried your solution but it's still not handling the exception. – nehacharya May 14 '18 at 12:02
  • Ok, why do you need @Slf4j @EnableWebMvc in `HttpClientErrorHandler` ? Please try removing those and try to place debug breakpoint in `HttpClientErrorHandler` when exception occurs. try and check if it helps. – rdj7 May 14 '18 at 13:41