I’m finding myself writing alot of retry loops that look like
int triesRemaining = 3; while (triesRemaining > 0) { try { <MY FUNCTION CALL> LOGGER.info("success"); break; } catch (Exception e) { if (e.getCause() instanceof SocketTimeoutException) { triesRemaining--; LOGGER.info(e.getMessage() + " trying again. Tries Remaining: " + triesRemaining); } else { LOGGER.error(e.getMessage(), e); return; } } } if (triesRemaining == 0) { LOGGER.error("Failed over too many times"); }
I want to write a generic function that accepts a Lambda and only retries on a specific error (in the above case thats SocketTimeoutException
). I’ve seen some functions that accept a Runnable
which is fine, but they don’t seem to allow limiting to specific exceptions.
Any advice?
Advertisement
Answer
Have a look to org.springframework.retry
There is an annotation @Retryable which corresponding to your need. You can specify the type of exception to retry and configure the number of attempt, etc…