【问题标题】:How to throw exception from Spring AOP declarative retry methods?如何从 Spring AOP 声明式重试方法中抛出异常?
【发布时间】:2020-10-26 16:44:57
【问题描述】:

我正在使用 Spring Retry 在我的方法中实现一些重试处理。

我的应用程序中有一个数据访问层 (DAL),我的应用程序中有一个服务层。

我的服务层调用 DAL 进行远程连接以检索信息。如果 DAL 失败,它将重试。但是,如果重试次数失败,我想重新抛出异常。

在我当前的项目中,我与此非常相似:

@Configuration
@EnableRetry
public class Application {

    @Bean
    public Service service() {
        return new Service();
    }

}

@Service
class Service {

    @Autowired
    DataAccessLayer dal;

    public void doSomethingWithFoo() {
        Foo foo = dal.getFoo()
        // do something with Foo
    }

}

@Service
class DataAccessLayer {
    @Retryable(RemoteAccessException.class)
    public Foo getFoo() {
        // call remote HTTP service to get Foo
    }
    @Recover
    public Foo recover(RemoteAccessException e) {
       // log the error?
       // how to rethrow such that DataAccessLayer.getFoo() shows it throws an exception as well?
    }
}

我的应用程序有一个服务,该服务调用 DataAccessLayer getFoo。如果getFoo 多次失败,DAL 将处理重试。如果它在那之后失败了,我希望我的服务层对此做点什么。但是,我不确定如何让人们知道这一点。我正在使用 intelliJ,当我尝试在 @Recover recover 方法中使用 throw e; 时,我没有收到任何警告 DataAccessLayer.getFoo 抛出任何异常。我不确定它是否会。但我希望 IDE 警告我,当重试失败时,将抛出一个新异常,让服务层知道期待它。否则,如果它调用dal.getFoo,它不知道处理任何错误。这通常是如何处理的?我不应该使用 AOP 声明式风格并使用命令式吗?

【问题讨论】:

  • 猜测没有警告,因为org.springframework.remoting.RemoteAccessException 扩展了RuntimeException

标签: spring spring-boot exception spring-retry


【解决方案1】:

您可以更改getFoo()(和recover())以添加throws <some checked exception>并将RemoteAccessException包裹在其中(在recover()中)。

这将强制服务层捕获该异常。

【讨论】:

  • 嗨,Gary,感谢您的参与!是的,我发现我可以做到这一点,我唯一希望的就是“强制”将throws 添加到我的方法中。如果重试次数用尽,该方法仍会抛出异常,但不会在编译时捕获。
  • 知道了。我将深入了解这些。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-20
  • 1970-01-01
  • 2023-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-23
相关资源
最近更新 更多