Spring / Spring Retry Interview Questions
How do you implement retry with a custom exception condition using RetryPolicy?
Sometimes the retry decision cannot be based on exception type alone — it needs to inspect the exception message, error code inside the exception, or a response payload embedded in a custom exception. In this case, you implement a custom RetryPolicy or use SimpleRetryPolicy with a map and a subclass override.
Custom policy inspecting exception detail:
public class HttpStatusRetryPolicy extends SimpleRetryPolicy { public HttpStatusRetryPolicy(int maxAttempts) { super(maxAttempts, Collections.singletonMap(MyApiException.class, true)); } @Override public boolean canRetry(RetryContext context) { Throwable t = context.getLastThrowable(); if (t instanceof MyApiException ex) { // Only retry on 503 or 429, not on 4xx int status = ex.getStatusCode(); boolean retryable = (status == 503 || status == 429); return retryable && context.getRetryCount() < getMaxAttempts(); } return super.canRetry(context); } }
Register it on RetryTemplate:
RetryTemplate template = new RetryTemplate(); template.setRetryPolicy(new HttpStatusRetryPolicy(4)); template.setBackOffPolicy(new ExponentialBackOffPolicy());
This pattern is valuable when integrating with APIs that return domain-specific error codes inside the exception, where a 400 with error code RATE_LIMITED should be retried but a 400 with INVALID_INPUT should not.
More Related questions...