[history] Added try-else behaviour
This commit is contained in:
parent
15146e02aa
commit
1b9bf5e49f
@ -3,21 +3,27 @@ package ru.landgrafhomyak.utility.highlevel_try_finally
|
|||||||
import kotlin.contracts.InvocationKind
|
import kotlin.contracts.InvocationKind
|
||||||
import kotlin.contracts.contract
|
import kotlin.contracts.contract
|
||||||
|
|
||||||
inline fun <R> safeAutoClose(onError: () -> Unit = {}, action: () -> R): R {
|
inline fun <R> safeAutoClose(onError: () -> Unit = {}, onSuccess: () -> Unit = {}, action: () -> R): R {
|
||||||
contract {
|
contract {
|
||||||
callsInPlace(action, InvocationKind.EXACTLY_ONCE)
|
callsInPlace(action, InvocationKind.EXACTLY_ONCE)
|
||||||
callsInPlace(onError, InvocationKind.AT_MOST_ONCE)
|
callsInPlace(onError, InvocationKind.AT_MOST_ONCE)
|
||||||
|
callsInPlace(onSuccess, InvocationKind.EXACTLY_ONCE)
|
||||||
}
|
}
|
||||||
val ret: R
|
val ret: R
|
||||||
|
var wasError = false
|
||||||
try {
|
try {
|
||||||
ret = action()
|
ret = action()
|
||||||
} catch (e1: Throwable) {
|
} catch (e1: Throwable) {
|
||||||
|
wasError = true
|
||||||
try {
|
try {
|
||||||
onError()
|
onError()
|
||||||
} catch (e2: Throwable) {
|
} catch (e2: Throwable) {
|
||||||
e1.addSuppressed(e2)
|
e1.addSuppressed(e2)
|
||||||
}
|
}
|
||||||
throw e1
|
throw e1
|
||||||
|
} finally {
|
||||||
|
if (!wasError)
|
||||||
|
onSuccess()
|
||||||
}
|
}
|
||||||
return ret
|
return ret
|
||||||
}
|
}
|
Loading…
Reference in New Issue
Block a user