d531df1643
This method can be useful when overriding a throwing Kotlin method in Swift or Obj-C. In this case, a user can call asError to wrap Kotlin exception to (NS)Error and then throw it to Kotlin, which will unwrap it back. ^KT-45127 Fixed
39 lines
993 B
Kotlin
39 lines
993 B
Kotlin
package throwableAsError
|
|
|
|
import kotlin.coroutines.*
|
|
|
|
class ThrowableAsError : Throwable()
|
|
|
|
interface ThrowsThrowableAsError {
|
|
@Throws(Throwable::class)
|
|
fun throwError()
|
|
}
|
|
|
|
fun callAndCatchThrowableAsError(throwsThrowableAsError: ThrowsThrowableAsError): ThrowableAsError? {
|
|
try {
|
|
throwsThrowableAsError.throwError()
|
|
} catch (e: ThrowableAsError) {
|
|
return e
|
|
}
|
|
|
|
return null
|
|
}
|
|
|
|
interface ThrowsThrowableAsErrorSuspend {
|
|
suspend fun throwError()
|
|
}
|
|
|
|
fun callAndCatchThrowableAsErrorSuspend(throwsThrowableAsErrorSuspend: ThrowsThrowableAsErrorSuspend): ThrowableAsError? {
|
|
var throwable: ThrowableAsError? = null
|
|
suspend {
|
|
throwsThrowableAsErrorSuspend.throwError()
|
|
}.startCoroutine(object : Continuation<Unit> {
|
|
override val context = EmptyCoroutineContext
|
|
override fun resumeWith(result: Result<Unit>) {
|
|
throwable = result.exceptionOrNull() as? ThrowableAsError
|
|
}
|
|
})
|
|
|
|
return throwable
|
|
}
|