Why does launch swallow exceptions in kotlin coroutines?

吃可爱长大的小学妹 提交于 2019-12-10 16:25:58

问题


The following test succeeds with Process finished with exit code 0. Note, this test does print the exception to the logs, but does not fail the test (which is the behavior I want).

@Test
fun why_does_this_test_pass() {
    val job = launch(Unconfined) {
        throw IllegalStateException("why does this exception not fail the test?")
    }

    // because of `Unconfined` dispatcher, exception is thrown before test function completes
}

As expected, this test fails with Process finished with exit code 255

@Test
fun as_expected_this_test_fails() {
    throw IllegalStateException("this exception fails the test")
}

Why do these tests not behave the same way?


回答1:


Compare your test with the following one that does not use any coroutines, but starts a new thread instead:

@Test
fun why_does_this_test_pass() {
    val job = thread { // <-- NOTE: Changed here
        throw IllegalStateException("why does this exception not fail the test?")
    }
    // NOTE: No need for runBlocking any more
    job.join() // ensures exception is thrown before test function completes
}

What happens here? Just like the test with launch, this test passes if you run it, but the exception gets printed on the console.

So, using launch to start a new coroutine is very much like using thread to start a new thread. If it fails, the error gets handled by uncaught exception handler in thread and by CoroutineExceptionHandler (see it in the docs) by launch. Exceptions in launch are not swallowed, but are handled by the coroutine exception handler.

If you want exception to propagate to the test, you shall replace launch with async and replace join with await in your code. See also this question: What is the difference between launch/join and async/await in Kotlin coroutines

UPDATE: Kotlin coroutines had recently introduced the concept of "Structured Concurrency" to avoid this kind of exception loss. The code in this question does not compile anymore. To compile it, you'd have to either explicitly say GlobalScope.launch (as in "I confirm that it Ok to loose my exceptions, here is my signature") or wrap the test into runBlocking { ... }, in which case exception is not lost.




回答2:


I was able to create an exception throwing CoroutineContext for tests.

val coroutineContext = Unconfined + CoroutineExceptionHandler { _, throwable ->
        throw throwable
    }

Though this would probably not be suitable for production. Maybe need to catch cancellation exceptions or something, I'm not sure




回答3:


A custom test rule so far seems to be the best solution.

/**
 * Coroutines can throw exceptions that can go unnoticed by the JUnit Test Runner which will pass
 * a test that should have failed. This rule will ensure the test fails, provided that you use the
 * [CoroutineContext] provided by [dispatcher].
 */
class CoroutineExceptionRule : TestWatcher(), TestRule {

    private val exceptions = Collections.synchronizedList(mutableListOf<Throwable>())

    val dispatcher: CoroutineContext
        get() = Unconfined + CoroutineExceptionHandler { _, throwable ->
            // I want to hook into test lifecycle and fail test immediately here
            exceptions.add(throwable)
            // this throw will not always fail the test. this does print the stacktrace at least
            throw throwable 
        }

    override fun starting(description: Description) {
        // exceptions from a previous test execution should not fail this test
        exceptions.clear()
    }

    override fun finished(description: Description) {
        // instead of waiting for test to finish to fail it
        exceptions.forEach { throw AssertionError(it) }
    }
}

I'm hoping to improve it via this post though



来源:https://stackoverflow.com/questions/50707785/why-does-launch-swallow-exceptions-in-kotlin-coroutines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!