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.
- Loading branch information
1 parent
d5c7457
commit a297dd0
Showing
4 changed files
with
52 additions
and
6 deletions.
There are no files selected for viewing
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
21 changes: 16 additions & 5 deletions
21
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,24 @@ | ||
package uk.gov.justice.digital.hmpps.retry | ||
|
||
fun <T> retry(maxRetries: Int, code: () -> T): T { | ||
var throwable: Throwable? = null | ||
(1..maxRetries).forEach { _ -> | ||
import kotlin.reflect.KClass | ||
|
||
fun <T> retry(maxRetries: Int, exceptions: List<KClass<out Exception>> = listOf(Exception::class), 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) { | ||
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