File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11package to.bitkit.ext
22
3+ import kotlinx.coroutines.CancellationException
34import kotlinx.coroutines.Job
45import 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+
617fun Job.logCompletion (name : String = "") = invokeOnCompletion { err ->
718 if (err != null ) {
819 Logger .verbose(" Coroutine '$name ' error: ${err.message} " )
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments