微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决Spring Cloud Stream和Spring RetryTemplate处理嵌套异常

我有一个使用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设置的配置

解决方法

您需要在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) {

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。