0
  • Sample interceptor code
package com.my.interceptor;

public class MyInterceptor implements HandlerInterceptor {
  @Override
  public boolean preHandle( ... ) throws Exception {
    throw new Exception("test exception"); // throw test exception
  }
}
  • Sample controller code
package com.my.controller;

@RestController
@RequiredArgsConstructor
public MyController {
  @GetMapping( "/my" )
  public ResponseEntity getMy() {
    ...
  }
}
  • Sample exception handler code
package com.my.handler;

@RestControllerAdvice( basePackages = { "com.my.interceptor" } ) // Doesn't handle interceptor
// @RestControllerAdvice( basePackages = { "com.my.controller" } ) // Handle both interceptor and controller
public class MyExceptionHandler extends ResponseEntityExceptionHandler {
  @ExceptionHandler( value = { Exception.class } )
  public void handleException( HttpServletRequest request, Exception e) {
    ...
  }
}

I want to handle exception from interceptor without creating custom exceptions.

But basePackages = { "com.my.interceptor" } in MyExceptionHandler doesn't handle exception from interceptor.

When I change basePackages to basePackages = { "com.my.controller" }, it handles both interceptor and controller.

Why this happen and how can I handle interceptor's exception only?

Rurien
  • 359
  • 1
  • 13

0 Answers0