Skip to content

Instantly share code, notes, and snippets.

@jaecktec
Created December 18, 2019 12:23
Show Gist options
  • Save jaecktec/88563970d8e1e45f3a03824573aa7712 to your computer and use it in GitHub Desktop.
Save jaecktec/88563970d8e1e45f3a03824573aa7712 to your computer and use it in GitHub Desktop.
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