Valeriy K.
Valeriy K.

Reputation: 2906

Handle only custom exception in spring retry

I want to retry only custom exceptions in Spring retry. But retryTemplate retries all exceptions. My code:

    try {
            getRetryTemplate().execute((RetryCallback<Void, IOException>) context -> {

                throw new RuntimeException("ddd"); // don't need to retry
            });
        } catch (IOException e) {
            log.error("");
        } catch (Throwable throwable) {
            log.error("Error .", throwable); // I want catch exception after first attempt
        }

private RetryTemplate getRetryTemplate() {
        RetryTemplate retryTemplate = new RetryTemplate();

        ExponentialBackOffPolicy exponentialBackOffPolicy = new ExponentialBackOffPolicy();
        exponentialBackOffPolicy.setInitialInterval(INITIAL_INTERVAL_FOR_RETRYING);
        retryTemplate.setBackOffPolicy(exponentialBackOffPolicy);

        SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
        retryPolicy.setMaxAttempts(MAX_ATTEMPTS);
        retryTemplate.setRetryPolicy(retryPolicy);

        return retryTemplate;
    }

I expect that retrier will retry only after IOException but it retry after all exceptions.

Upvotes: 1

Views: 5034

Answers (1)

Valeriy K.
Valeriy K.

Reputation: 2906

I don't understand for what purposes Exception type in RetryCallback but I found that I can specify desired behaviour in RetryTemplate with ExceptionClassifierRetryPolicy:

private RetryTemplate getRetryTemplate() {
    RetryTemplate retryTemplate = new RetryTemplate();

    ExponentialBackOffPolicy exponentialBackOffPolicy = new ExponentialBackOffPolicy();
    exponentialBackOffPolicy.setInitialInterval(INITIAL_INTERVAL_FOR_RETRYING);
    retryTemplate.setBackOffPolicy(exponentialBackOffPolicy);

    SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
    retryPolicy.setMaxAttempts(MAX_ATTEMPTS);

    ExceptionClassifierRetryPolicy exceptionClassifierRetryPolicy = new ExceptionClassifierRetryPolicy();
    Map<Class<? extends Throwable>, RetryPolicy> policyMap = new HashMap<>();
    policyMap.put(IOException.class, retryPolicy);
    exceptionClassifierRetryPolicy.setPolicyMap(policyMap);
    retryTemplate.setRetryPolicy(exceptionClassifierRetryPolicy);

    return retryTemplate;
}

With this configuration only IOException will be retried.

Upvotes: 2

Related Questions