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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
