2

I followed this and created Executor, Callable and ExecutorConfig exactly as described in the answer. Now I started getting HttpServletRequest object in AOP code but the object doesn't contain anything. for example request.getRequestURI() is giving NULL. In my AOP code I just need to read the Throwable and HttpServletRequest objects to store error information and some important request headers along with the URI in a table.

Here is my AOP code -

@Aspect
@Component
public class ErrorAspect {

    private static final String EXCEPTION_EXECUTION_PATH = "execution(* com.myproject.*.service.impl.*.*(..))";

    @Autowired
    private ErrorHelper         errorHelper;

    @Pointcut( EXCEPTION_EXECUTION_PATH)
    public void atExecutionExcpetion() {
    }

    @AfterThrowing( value = "atExecutionExcpetion()", throwing = "error")
    public void storeErrorAfterThrowing( Throwable error) {
        errorHelper.saveError(error);
    }
}

And saveError() method in ErrorHelper is -

public void saveError( Throwable error) {
        HttpServletRequest request = null;
        if (RequestContextHolder.getRequestAttributes() != null) {
            request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        }
        Error error = prepareError(request, error);
        CompletableFuture.runAsync(() -> insertError(error));
    }  

private Error prepareError( HttpServletRequest request, Throwable error) {
    Error error = new Error();
    if (request == null) {
        String process = Constants.AUTO_JOB + LocalDateTime.now(ZoneId.of(PST_ZONE_ID)).toString().replaceAll("-", "");
        error.setProcessType(Constants.AUTO_JOB);
        error.setApplicationId(process);
        error.setSessionId(process);
        error.setUri(NA);
    } else {
        error.setProcessType(request.getHeader(Constants.PROCESS_ID));
        error.setApplicationId(request.getHeader(Constants.APPLICATION_ID));
        error.setSessionId(request.getHeader(Constants.SESSION_ID));
        error.setUri(request.getRequestURI());
    }
    error.setEventDateTime(Instant.now());
    error.setErrorType(getErrorType(error));
    error.setErrorMessage(getErrorMessage(error));
    return error;
}

This works perfectly fine with synchronous calls. But for @Async calls there is no header/uri information in the request object.

Saurabh
  • 2,384
  • 6
  • 37
  • 52

1 Answers1

1

Created a decorator and copy required request attribute to MDC. Here is the decorator code -

public class ContextAwareExecutorDecorator implements Executor, TaskExecutor {

    private final Executor executor;

    public ContextAwareExecutorDecorator( Executor executor) {
        this.executor = executor;
    }

    @Override
    public void execute( Runnable command) {
        Runnable ctxAwareCommand = decorateContextAware(command);
        executor.execute(ctxAwareCommand);
    }

    private Runnable decorateContextAware( Runnable command) {
        RequestAttributes originalRequestContext = RequestContextHolder.currentRequestAttributes();

        if (originalRequestContext != null) {
            HttpServletRequest request = ((ServletRequestAttributes) originalRequestContext).getRequest();
            copyRequestToMDC(request);
        }

        final Map<String, String> originalContextCopy = MDC.getCopyOfContextMap();
        return () -> {
            try {
                if (originalRequestContext != null) {
                    RequestContextHolder.setRequestAttributes(originalRequestContext);
                }
                MDC.setContextMap(originalContextCopy);
                command.run();
            } finally {
                MDC.clear();
                RequestContextHolder.resetRequestAttributes();
            }
        };
    }

    private void copyRequestToMDC( HttpServletRequest request) {
        if (request != null) {
            MDC.put("requestURI", request.getRequestURI());
            // Set other required attributes
        }
    }
}

Here is the Executor config -

@Configuration
public class ExecutorConfig extends AsyncConfigurerSupport {

    @Override
    @Bean( "asyncTaskExecutor")
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setThreadNamePrefix("contextAwareExecutor-");
        executor.initialize();
        return new ContextAwareExecutorDecorator(executor);
    }

    @Override
    @Bean
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new CustomAsyncExceptionHandler();
    }
}

Now in AOP code I am able to retrieve attributes from MDC.

error.setUri(MDC.get("requestURI"));
Saurabh
  • 2,384
  • 6
  • 37
  • 52
  • I have same problem here as yo can see here, https://stackoverflow.com/questions/63116739/java-lang-illegalstateexception-no-thread-bound-request-found-when-using-reques could you help me to solve this? what is MDC in your codes? – Rasool Ghafari Jul 29 '20 at 05:06