Spring Cloud Stream和Spring RetryTemplate处理嵌套异常

时间:2020-08-28 11:19:25

标签: spring-cloud-stream spring-retry spring-cloud-stream-binder-kafka

我有一个使用Kafka活页夹的Spring Cloud Stream项目,我想添加重试功能,我试图使用RetryTemplate并指定要处理的某些异常,但是由于MessageTransformationException包装了任何异常,我可以用我想要的方式配置它。有没有办法处理嵌套异常?

重试模板

@StreamRetryTemplate
public RetryTemplate myRetryTemplate() {
  RetryTemplate retryTemplate = new RetryTemplate();
 
  ExceptionClassifierRetryPolicy exceptionClassifierRetryPolicy =
      new ExceptionClassifierRetryPolicy();
  Map<Class<? extends Throwable>, RetryPolicy> policyMap = new HashMap<>();
  policyMap.put(MyException.class, new SimpleRetryPolicy(4));
  exceptionClassifierRetryPolicy.setPolicyMap(policyMap);
  retryTemplate.setRetryPolicy(exceptionClassifierRetryPolicy);
  return retryTemplate;
}

Stacktrace

org.springframework.integration.transformer.MessageTransformationException: Failed to transform Message in bean '...' for component ‘...'; nested exception is org.springframework.messaging.MessageHandlingException: error occurred during processing message in 'MethodInvokingMessageProcessor' [org.springframework.integration.handler.MethodInvokingMessageProcessor@4dba2d07]; nested exception is MyException

因此它会忽略我为MyException设置的配置

1 个答案:

答案 0 :(得分:0)

您需要在return element;中将traverseCauses设置为true

SimpleRetryPolicy

所以:

/**
 * Create a {@link SimpleRetryPolicy} with the specified number of retry attempts. If
 * traverseCauses is true, the exception causes will be traversed until a match is
 * found.
 * @param maxAttempts the maximum number of attempts
 * @param retryableExceptions the map of exceptions that are retryable based on the
 * map value (true/false).
 * @param traverseCauses is this cause traversable
 */
public SimpleRetryPolicy(int maxAttempts, Map<Class<? extends Throwable>, Boolean> retryableExceptions,
        boolean traverseCauses) {