setOnFailureExpression не работает для #root и #exception - PullRequest
0 голосов
/ 12 февраля 2019
@Bean
public ExpressionEvaluatingRequestHandlerAdvice after() {
    logger.debug("Evaluating expression advice. ");
    ExpressionEvaluatingRequestHandlerAdvice advice = new ExpressionEvaluatingRequestHandlerAdvice();
    advice.setTrapException(true);
    advice.setOnFailureExpressionString("#root");
    advice.setSuccessChannel(rtwSourceDeletionChannel());
    advice.setFailureChannel(rtwFtpFailureHandleChannel());
    advice.setPropagateEvaluationFailures(true);
    return advice;
}

@Bean
public IntegrationFlow rtwFtpFailureHandlerFlow() {
    return IntegrationFlows
                .from(rtwFtpFailureHandleChannel())
                .handle( msg -> {
                    // code to delete all files except source. 
                    logger.debug("Handling Failure......");

                    List<String> transitPaths = (List<String>) msg.getHeaders().get(AdviceHandlerMessageHeaders.TRANSIT_PATHS); 
                    String sourcePath = (String) msg.getHeaders().get(AdviceHandlerMessageHeaders.SOURCE); 

                    System.out.println("payload: " + msg.getPayload());
                    })
                .get();
}

Создает тот же результат для #root и #exception, как показано ниже:

payload: org.springframework.integration.handler.advice.ExpressionEvaluatingRequestHandlerAdvice$MessageHandlingExpressionEvaluatingAdviceException: Handler Failed; nested exception is org.springframework.messaging.MessageHandlingException: error occurred in message handler [rtwFtpOutboundHandler]; nested exception is org.springframework.messaging.MessagingException: Failed to execute on session; nested exception is org.springframework.integration.util.PoolItemNotAvailableException: Failed to obtain pooled item, failedMessage=GenericMessage [payload=sample.pdf, headers={file_name=sample.pdf, TRANSIT_PATHS=[\\localhost\atala-capture-upload, sample.tif], SOURCE=\\localhost\atala-capture-upload, file_originalFile=\\localhost\atala-capture-upload\sample.tif, id=746728a4-9b9e-847f-6c2c-29aa8a4a5fd6, file_relativePath=sample.tif, timestamp=1549922458296}], failedMessage=GenericMessage [payload=sample.pdf, headers={file_name=sample.pdf, TRANSIT_PATHS=[\\localhost\atala-capture-upload, sample.tif], SOURCE=\\localhost\atala-capture-upload, file_originalFile=\\localhost\atala-capture-upload\sample.tif, id=746728a4-9b9e-847f-6c2c-29aa8a4a5fd6, file_relativePath=sample.tif, timestamp=1549922458296}]

1 Ответ

0 голосов
/ 12 февраля 2019

Это работает, как и ожидалось.

Логика выглядит следующим образом:

try {
        evalResult = this.onFailureExpression.getValue(prepareEvaluationContextToUse(exception), message);
    }
    catch (Exception e) {
        evalResult = e;
        logger.error("Failure expression evaluation failed for " + message + ": " + e.getMessage());
    }
    DestinationResolver<MessageChannel> channelResolver = getChannelResolver();
    if (this.failureChannel == null && this.failureChannelName != null && channelResolver != null) {
        this.failureChannel = channelResolver.resolveDestination(this.failureChannelName);
    }
    if (evalResult != null && this.failureChannel != null) {
        MessagingException messagingException =
                new MessageHandlingExpressionEvaluatingAdviceException(message, "Handler Failed",
                        unwrapThrowableIfNecessary(exception), evalResult);
        ErrorMessage errorMessage = new ErrorMessage(messagingException);
        this.messagingTemplate.send(this.failureChannel, errorMessage);
    }

Результат оценки onFailureExpression добавляется к MessageHandlingExpressionEvaluatingAdviceException как свойство.И это исключение переносится в ErrorMessage для отправки на настроенный failureChannel.

Итак, ваш код пока верен, если только вы не пропустите тот факт, что payload сообщения, которое вы обрабатываетев этом rtwFtpFailureHandlerFlow является точно упомянутым MessageHandlingExpressionEvaluatingAdviceException.Чтобы получить доступ к результату вашего выражения, вам нужно привести payload к этому исключению и вызвать его getEvaluationResult().С другой стороны, вам даже не нужно иметь никаких сложных выражений, поскольку сообщение запроса доступно как failedMessage этого исключения.Плюс реальная неудача в причине этого исключения.

Для получения дополнительной информации см. Документы: https://docs.spring.io/spring-integration/docs/current/reference/html/messaging-endpoints-chapter.html#expression-advice

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...