alex
alex

Reputation: 2193

How to throw exception from Spring AOP declarative retry methods?

I'm implementing some retry handling in my methods using Spring Retry.

I have a Data Access Layer (DAL) in my application and a Service Layer in my application.

My Service layer calls the DAL to make a remote connection to retrieve information. If the DAL fails it will retry. However, if the number of retries fails I would like to rethrow an exception.

In my current project I something very similar to this:

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

My Application has a Service and the Service calls DataAccessLayer getFoo. If getFoo fails a number of times the DAL will handle the retries. If it fail's after that I'd like my Service layer to do something about it. However I'm not sure how to let that be known. I'm using intelliJ and when I try to throw e; in the @Recover recover method I don't get any warnings that DataAccessLayer.getFoo throws any exceptions. I'm not sure if it will. But I'd like the IDE to warn me that when the retries fail a new exception will be thrown to let the Service layer know to expect it. Otherwise if it calls dal.getFoo it doesn't know to handle any errors. How is this typically handled? Should I not use the AOP declarative style and go for imperative?

Upvotes: 0

Views: 685

Answers (1)

Gary Russell
Gary Russell

Reputation: 174554

You can change getFoo() (and recover()) to add throws <some checked exception> and wrap the RemoteAccessException in it (in recover()).

That will force the service layer to catch that exception.

Upvotes: 1

Related Questions