generated from ministryofjustice/template-repository
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Browse files
Browse the repository at this point in the history
- Loading branch information
1 parent
a1d6464
commit 7f9ffc4
Showing
5 changed files
with
75 additions
and
6 deletions.
There are no files selected for viewing
29 changes: 24 additions & 5 deletions
29
libs/commons/src/main/kotlin/uk/gov/justice/digital/hmpps/retry/Retry.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,13 +1,32 @@ | ||
package uk.gov.justice.digital.hmpps.retry | ||
|
||
fun <T> retry(maxRetries: Int, code: () -> T): T { | ||
var throwable: Throwable? = null | ||
(1..maxRetries).forEach { _ -> | ||
import java.time.Duration | ||
import java.util.concurrent.TimeUnit | ||
import kotlin.reflect.KClass | ||
|
||
fun <T> retry( | ||
maxRetries: Int, | ||
exceptions: List<KClass<out Exception>> = listOf(Exception::class), | ||
delay: Duration = Duration.ofMillis(100), | ||
code: () -> T | ||
): T { | ||
var throwable: Throwable? | ||
(1..maxRetries).forEach { count -> | ||
try { | ||
return code() | ||
} catch (e: Throwable) { | ||
throwable = e | ||
val matchedException = exceptions.firstOrNull { it.isInstance(e) } | ||
throwable = if (matchedException != null && count < maxRetries) { | ||
null | ||
} else { | ||
e | ||
} | ||
if (throwable == null) { | ||
TimeUnit.MILLISECONDS.sleep(delay.toMillis() * count * count) | ||
} else { | ||
throw throwable!! | ||
} | ||
} | ||
} | ||
throw throwable!! | ||
throw RuntimeException("unknown error") | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters