Created
December 18, 2019 12:23
-
-
Save jaecktec/88563970d8e1e45f3a03824573aa7712 to your computer and use it in GitHub Desktop.
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
infix fun <T, E : Exception> Any.tryForCause(init: () -> T): TryForCause<T, E> { | |
return TryForCause<T, E>().execute(init) | |
} | |
class TryForCause<T, out E : Exception> { | |
private var throwable: Exception? = null | |
private var result: Any? = null | |
fun execute(init: () -> T): TryForCause<T, E> { | |
try { | |
result = init() | |
} catch (e: Exception) { | |
throwable = e | |
} | |
return this | |
} | |
@Suppress("UNCHECKED_CAST") | |
infix fun catchCause(init: (E) -> T): T { | |
val ex = throwable | |
if (ex != null && ex.cause.checkCastable<E>()) { | |
return init(ex.cause as E) | |
} | |
ex?.run { throw ex } | |
return result as T | |
} | |
private fun <T : Any> Any?.checkCastable(): Boolean { | |
return try { | |
@Suppress("UNCHECKED_CAST") | |
this as T | |
true | |
} catch (e: Exception) { | |
println(e.message) | |
false | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment