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.