2020-09-24 02:27:16 +00:00
|
|
|
package dev.inmo.micro_utils.coroutines
|
|
|
|
|
|
|
|
import kotlinx.coroutines.CoroutineScope
|
|
|
|
import kotlinx.coroutines.supervisorScope
|
2020-12-22 09:16:06 +00:00
|
|
|
import kotlin.coroutines.CoroutineContext
|
|
|
|
import kotlin.coroutines.coroutineContext
|
2020-09-24 02:27:16 +00:00
|
|
|
|
|
|
|
typealias ExceptionHandler<T> = suspend (Throwable) -> T
|
2020-12-22 09:16:06 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* This instance will be used in all calls of [safely] where exception handler has not been passed
|
|
|
|
*/
|
|
|
|
var defaultSafelyExceptionHandler: ExceptionHandler<Nothing> = { throw it }
|
|
|
|
|
|
|
|
class SafelyExceptionHandlerKey<T> : CoroutineContext.Key<SafelyExceptionHandler<T>>
|
|
|
|
inline fun <T> safelyExceptionHandlerKey() = SafelyExceptionHandlerKey<T>()
|
|
|
|
class SafelyExceptionHandler<T>(
|
|
|
|
val handler: ExceptionHandler<T>
|
|
|
|
) : CoroutineContext.Element {
|
|
|
|
|
|
|
|
override val key: CoroutineContext.Key<*> = safelyExceptionHandlerKey<T>()
|
|
|
|
}
|
|
|
|
|
2020-09-24 02:27:16 +00:00
|
|
|
/**
|
|
|
|
* It will run [block] inside of [supervisorScope] to avoid problems with catching of exceptions
|
|
|
|
*
|
|
|
|
* @param [onException] Will be called when happen exception inside of [block]. By default will throw exception - this
|
|
|
|
* exception will be available for catching
|
2020-12-22 09:16:06 +00:00
|
|
|
*
|
|
|
|
* @see defaultSafelyExceptionHandler
|
|
|
|
* @see safelyWithoutExceptions
|
2020-09-24 02:27:16 +00:00
|
|
|
*/
|
|
|
|
suspend inline fun <T> safely(
|
2020-12-22 09:16:06 +00:00
|
|
|
noinline onException: ExceptionHandler<T> = defaultSafelyExceptionHandler,
|
2020-09-24 02:27:16 +00:00
|
|
|
noinline block: suspend CoroutineScope.() -> T
|
|
|
|
): T {
|
|
|
|
return try {
|
|
|
|
supervisorScope(block)
|
|
|
|
} catch (e: Throwable) {
|
2020-12-22 09:16:06 +00:00
|
|
|
val handler = if (onException == defaultSafelyExceptionHandler) {
|
|
|
|
coroutineContext[safelyExceptionHandlerKey<T>()] ?.handler ?: onException
|
|
|
|
} else {
|
|
|
|
onException
|
|
|
|
}
|
|
|
|
handler(e)
|
2020-09-24 02:27:16 +00:00
|
|
|
}
|
|
|
|
}
|
2020-11-02 15:25:33 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Shortcut for [safely] without exception handler (instead of this you will receive null as a result)
|
|
|
|
*/
|
|
|
|
suspend inline fun <T> safelyWithoutExceptions(
|
|
|
|
noinline block: suspend CoroutineScope.() -> T
|
|
|
|
): T? = safely({ null }, block)
|