This commit is contained in:
2025-02-19 23:29:49 +06:00
parent b589142d9f
commit de72843b8e
2 changed files with 28 additions and 0 deletions

View File

@@ -0,0 +1,26 @@
package dev.inmo.micro_utils.common
/**
* Will try to execute [action] and, if any exception will happen, execution will be retried.
* This process will happen at most [count] times. There is no any limits on [count] value, but [action] will run at
* least once and [retryOnFailure] will return its result if it is successful
*/
inline fun <T> retryOnFailure(count: Int, action: () -> T): T {
var triesCount = 0
while (true) {
val result = runCatching {
action()
}.onFailure {
triesCount++
if (triesCount >= count) {
throw it
} else {
null
}
}
if (result.isSuccess) return result.getOrThrow()
}
error("Unreachable code: retry must throw latest exception if error happen or success value if not")
}