Skip to content

Commit 2c7c0cb

Browse files
committed
chore: create helper for re-throw CancellationException
1 parent d1c4092 commit 2c7c0cb

2 files changed

Lines changed: 46 additions & 0 deletions

File tree

app/src/main/java/to/bitkit/ext/Coroutines.kt

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,19 @@
11
package to.bitkit.ext
22

3+
import kotlinx.coroutines.CancellationException
34
import kotlinx.coroutines.Job
45
import to.bitkit.utils.Logger
56

7+
@Suppress("TooGenericExceptionCaught")
8+
suspend inline fun <R> runSuspendCatching(block: () -> R): Result<R> =
9+
try {
10+
Result.success(block())
11+
} catch (c: CancellationException) {
12+
throw c
13+
} catch (e: Throwable) {
14+
Result.failure(e)
15+
}
16+
617
fun Job.logCompletion(name: String = "") = invokeOnCompletion { err ->
718
if (err != null) {
819
Logger.verbose("Coroutine '$name' error: ${err.message}")
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package to.bitkit.ext
2+
3+
import kotlinx.coroutines.CancellationException
4+
import org.junit.Test
5+
import to.bitkit.test.BaseUnitTest
6+
import kotlin.test.assertEquals
7+
import kotlin.test.assertFailsWith
8+
import kotlin.test.assertTrue
9+
10+
class CoroutinesTest : BaseUnitTest() {
11+
12+
@Test
13+
fun `runSuspendCatching wraps a successful result`() = test {
14+
val result = runSuspendCatching { 42 }
15+
16+
assertEquals(42, result.getOrNull())
17+
}
18+
19+
@Test
20+
fun `runSuspendCatching wraps a thrown exception as failure`() = test {
21+
val error = IllegalStateException("boom")
22+
23+
val result = runSuspendCatching { throw error }
24+
25+
assertTrue(result.isFailure)
26+
assertEquals(error, result.exceptionOrNull())
27+
}
28+
29+
@Test
30+
fun `runSuspendCatching re-throws CancellationException`() = test {
31+
assertFailsWith<CancellationException> {
32+
runSuspendCatching { throw CancellationException("cancelled") }
33+
}
34+
}
35+
}

0 commit comments

Comments
 (0)