在处理@Async方法的AOP中的异常时丢失HttpServletRequest对象

时间:2019-06-19 23:18:18

标签: java spring spring-boot spring-aop

我遵循this并完全按照答案中的描述创建了Executor,Callable和ExecutorConfig。现在,我开始在AOP代码中获取HttpServletRequest对象,但是该对象不包含任何内容。例如request.getRequestURI()给出NULL。 在我的AOP代码中,我只需要读取Throwable和HttpServletRequest对象即可在表中存储错误信息和一些重要的请求标头以及URI。

这是我的AOP代码-

@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);
    }
}

ErrorHelper中的saveError()方法是-

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;
}

这对于同步调用非常有效。但是对于@Async调用,请求对象中没有标题/ uri信息。

1 个答案:

答案 0 :(得分:0)

创建一个装饰器,并将所需的请求属性复制到MDC。这是装饰代码-

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
        }
    }
}

这是执行器配置-

@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();
    }
}

现在在AOP代码中,我能够从MDC检索属性。

error.setUri(MDC.get("requestURI"));