0

I need to validate the HttpServletRequest for certain attribtues in my service layer before proceeding. I created @Before advice, Please note that AOP method throws Exception. I want exception thrown by this method should be handled by RestControllerAdvice. I can see that AOP method is being executed but DataNotValidException is not being handled by RestControllerAdvice. RestConrollerAdvice is working fine if there is any exception on the validation of other parameters or any exception in RestController.

@Before("execution(* com.mycom.service.app.myappName.handler*.*.*(..)) && args(httpServletRequest,..)" )
public void validateRequest(JoinPoint joinPoint, HttpServletRequest httpServletRequest) throws DataNotValidException {

This is my @RestControllerAdvice. I tried to override handleExceptionInternal as well.

public String handleLinkage(final HttpServletRequest httpServletRequest, @Valid UserLinkRequest userLinkReqeust, final HttpHeaders httpHeaders) {

    @RestControllerAdvice
    @Slf4j
    public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

        @ExceptionHandler(value = { InvalidFormatException.class, DataNotValidException.class, Exception.class,
                SQLException.class })
        private ResponseEntity<ResponseObjectData> handleAllException(Exception exception, HttpHeaders headers,
                WebRequest request, HandlerMethod handlerMethod) {
           // logErrorNBuildResponse
        }
    @Override
    protected ResponseEntity<Object> handleExceptionInternal(
            Exception ex, @Nullable Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {
        // logErrorNBuildResponse
     } }
Vikky
  • 1,123
  • 14
  • 16
  • `@Before` advice executes before the intercepted method is executed . When exception gets thrown from such an advice the control never reaches the actual method . That probably is the reason the controller advice didnt get involved in the exception handling. – R.G Mar 27 '20 at 17:17
  • @R.G This handler/service method is getting called by controller. So in stacktrace, Controller--> Hanlder's method. Yes, AOP method gets called before hander's method but after controller's method. – Vikky Mar 27 '20 at 17:43
  • My mistake, since the AOP was involved with request validation I assumed it is for a controller method. Could you please share the stack trace when the AOP throws exception ? – R.G Mar 27 '20 at 18:11
  • 1
    I actually resolved it, Issue was that advice method can have only those arguments in its signature which exception throwing method have or can provide. My AOP method was not having access to Headers so it could not provide Headers to RestControllerAdivce method. As soon as I created a new exception handler method in RestController without Headers as argument, RestControllerAdivce started working as expected. Thanks – Vikky Mar 27 '20 at 19:04

0 Answers0