Skip to content

Commit 1245d7e

Browse files
authored
Attempt to report uncaught exceptions in the test module (#3449)
When when a `Job` doesn't have a parent, failures in it can not be reported via structured concurrency. Instead, the mechanism of unhandled exceptions is used. If there is a `CoroutineExceptionHandler` in the coroutine context or registered as a `ServiceLoader` service, this gets notified, and otherwise, something platform-specific happens: on Native, the program crashes, and on the JVM, by default, the exception is just logged, though this is configurable via `Thread.setUncaughtExceptionHandler`. With tests on the JVM, this is an issue: we want exceptions not simply *logged*, we want them to fail the test, and this extends beyond just coroutines. However, JUnit does not override the uncaught exception handler, and uncaught exceptions do just get logged: <https://stackoverflow.com/questions/36648317/how-to-capture-all-uncaucht-exceptions-on-junit-tests> This is a problem with a widely-used `viewModelScope` on Android. This is a scope without a parent, and so the exceptions in it are uncaught. On Android, such uncaught exceptions crash the app by default, but in tests, they just get logged. Clearly, without overriding the behavior of uncaught exceptions, the tests are lacking. This can be solved on the test writers' side via `setUncaughtExceptionHandler`, but one has to remember to do that. In this commit, we attempt to solve this issue for the overwhelming majority of users. To that end, when the test framework is used, we collect the uncaught exceptions and report them at the end of a test. This approach is marginally less robust than `setUncaughtExceptionHandler`: if an exception happened after the last test using `kotlinx-coroutines-test`, it won't get reported, for example. `CoroutineExceptionHandler` is designed in such a way that, when it is used in a coroutine context, its presence means that the exceptions are safe in its care and will not be propagated further, but when used as a service, it has no such property. We, however, know that our `CoroutineExceptionHandler` reports the exceptions properly and they don't need to be further logged, and so we had to extend the behavior of mechanism for uncaught exception handling so that the handler throws a new kind of exception if the exception was processed successfully. Also, because there's no `ServiceLoader` mechanism on JS or Native, we had to refactor the whole uncaught exception handling mechanism a bit in the same vein as we had to adapt the `Main` dispatcher to `Dispatchers.setMain`: by introducing internal setter APIs that services have to call manually to register in. Fixes #1205 as thoroughly as we can, given the circumstances.
1 parent 747db9e commit 1245d7e

19 files changed

+396
-110
lines changed

integration-testing/src/jvmCoreTest/kotlin/ListAllCoroutineThrowableSubclassesTest.kt

+2-1
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,8 @@ class ListAllCoroutineThrowableSubclassesTest {
2727
"kotlinx.coroutines.JobCancellationException",
2828
"kotlinx.coroutines.internal.UndeliveredElementException",
2929
"kotlinx.coroutines.CompletionHandlerException",
30-
"kotlinx.coroutines.DiagnosticCoroutineContextException",
30+
"kotlinx.coroutines.internal.DiagnosticCoroutineContextException",
31+
"kotlinx.coroutines.internal.ExceptionSuccessfullyProcessed",
3132
"kotlinx.coroutines.CoroutinesInternalError",
3233
"kotlinx.coroutines.channels.ClosedSendChannelException",
3334
"kotlinx.coroutines.channels.ClosedReceiveChannelException",

kotlinx-coroutines-core/common/src/CoroutineExceptionHandler.kt

+3-4
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,9 @@
44

55
package kotlinx.coroutines
66

7+
import kotlinx.coroutines.internal.*
78
import kotlin.coroutines.*
89

9-
internal expect fun handleCoroutineExceptionImpl(context: CoroutineContext, exception: Throwable)
10-
1110
/**
1211
* Helper function for coroutine builder implementations to handle uncaught and unexpected exceptions in coroutines,
1312
* that could not be otherwise handled in a normal way through structured concurrency, saving them to a future, and
@@ -26,11 +25,11 @@ public fun handleCoroutineException(context: CoroutineContext, exception: Throwa
2625
return
2726
}
2827
} catch (t: Throwable) {
29-
handleCoroutineExceptionImpl(context, handlerException(exception, t))
28+
handleUncaughtCoroutineException(context, handlerException(exception, t))
3029
return
3130
}
3231
// If a handler is not present in the context or an exception was thrown, fallback to the global handler
33-
handleCoroutineExceptionImpl(context, exception)
32+
handleUncaughtCoroutineException(context, exception)
3433
}
3534

3635
internal fun handlerException(originalException: Throwable, thrownException: Throwable): Throwable {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
/*
2+
* Copyright 2016-2022 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
3+
*/
4+
5+
package kotlinx.coroutines.internal
6+
7+
import kotlinx.coroutines.*
8+
import kotlin.coroutines.*
9+
10+
/**
11+
* The list of globally installed [CoroutineExceptionHandler] instances that will be notified of any exceptions that
12+
* were not processed in any other manner.
13+
*/
14+
internal expect val platformExceptionHandlers: Collection<CoroutineExceptionHandler>
15+
16+
/**
17+
* Ensures that the given [callback] is present in the [platformExceptionHandlers] list.
18+
*/
19+
internal expect fun ensurePlatformExceptionHandlerLoaded(callback: CoroutineExceptionHandler)
20+
21+
/**
22+
* The platform-dependent global exception handler, used so that the exception is logged at least *somewhere*.
23+
*/
24+
internal expect fun propagateExceptionFinalResort(exception: Throwable)
25+
26+
/**
27+
* Deal with exceptions that happened in coroutines and weren't programmatically dealt with.
28+
*
29+
* First, it notifies every [CoroutineExceptionHandler] in the [platformExceptionHandlers] list.
30+
* If one of them throws [ExceptionSuccessfullyProcessed], it means that that handler believes that the exception was
31+
* dealt with sufficiently well and doesn't need any further processing.
32+
* Otherwise, the platform-dependent global exception handler is also invoked.
33+
*/
34+
internal fun handleUncaughtCoroutineException(context: CoroutineContext, exception: Throwable) {
35+
// use additional extension handlers
36+
for (handler in platformExceptionHandlers) {
37+
try {
38+
handler.handleException(context, exception)
39+
} catch (_: ExceptionSuccessfullyProcessed) {
40+
return
41+
} catch (t: Throwable) {
42+
propagateExceptionFinalResort(handlerException(exception, t))
43+
}
44+
}
45+
46+
try {
47+
exception.addSuppressed(DiagnosticCoroutineContextException(context))
48+
} catch (e: Throwable) {
49+
// addSuppressed is never user-defined and cannot normally throw with the only exception being OOM
50+
// we do ignore that just in case to definitely deliver the exception
51+
}
52+
propagateExceptionFinalResort(exception)
53+
}
54+
55+
/**
56+
* Private exception that is added to suppressed exceptions of the original exception
57+
* when it is reported to the last-ditch current thread 'uncaughtExceptionHandler'.
58+
*
59+
* The purpose of this exception is to add an otherwise inaccessible diagnostic information and to
60+
* be able to poke the context of the failing coroutine in the debugger.
61+
*/
62+
internal expect class DiagnosticCoroutineContextException(context: CoroutineContext) : RuntimeException
63+
64+
/**
65+
* A dummy exception that signifies that the exception was successfully processed by the handler and no further
66+
* action is required.
67+
*
68+
* Would be nicer if [CoroutineExceptionHandler] could return a boolean, but that would be a breaking change.
69+
* For now, we will take solace in knowledge that such exceptions are exceedingly rare, even rarer than globally
70+
* uncaught exceptions in general.
71+
*/
72+
internal object ExceptionSuccessfullyProcessed : Exception()

kotlinx-coroutines-core/js/src/CoroutineExceptionHandlerImpl.kt

-12
This file was deleted.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/*
2+
* Copyright 2016-2022 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
3+
*/
4+
5+
package kotlinx.coroutines.internal
6+
7+
import kotlinx.coroutines.*
8+
import kotlin.coroutines.*
9+
10+
private val platformExceptionHandlers_ = mutableSetOf<CoroutineExceptionHandler>()
11+
12+
internal actual val platformExceptionHandlers: Collection<CoroutineExceptionHandler>
13+
get() = platformExceptionHandlers_
14+
15+
internal actual fun ensurePlatformExceptionHandlerLoaded(callback: CoroutineExceptionHandler) {
16+
platformExceptionHandlers_ += callback
17+
}
18+
19+
internal actual fun propagateExceptionFinalResort(exception: Throwable) {
20+
// log exception
21+
console.error(exception)
22+
}
23+
24+
internal actual class DiagnosticCoroutineContextException actual constructor(context: CoroutineContext) :
25+
RuntimeException(context.toString())
26+

kotlinx-coroutines-core/jvm/src/CoroutineExceptionHandlerImpl.kt

-62
This file was deleted.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/*
2+
* Copyright 2016-2022 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
3+
*/
4+
5+
package kotlinx.coroutines.internal
6+
7+
import java.util.*
8+
import kotlinx.coroutines.*
9+
import kotlin.coroutines.*
10+
11+
/**
12+
* A list of globally installed [CoroutineExceptionHandler] instances.
13+
*
14+
* Note that Android may have dummy [Thread.contextClassLoader] which is used by one-argument [ServiceLoader.load] function,
15+
* see (https://stackoverflow.com/questions/13407006/android-class-loader-may-fail-for-processes-that-host-multiple-applications).
16+
* So here we explicitly use two-argument `load` with a class-loader of [CoroutineExceptionHandler] class.
17+
*
18+
* We are explicitly using the `ServiceLoader.load(MyClass::class.java, MyClass::class.java.classLoader).iterator()`
19+
* form of the ServiceLoader call to enable R8 optimization when compiled on Android.
20+
*/
21+
internal actual val platformExceptionHandlers: Collection<CoroutineExceptionHandler> = ServiceLoader.load(
22+
CoroutineExceptionHandler::class.java,
23+
CoroutineExceptionHandler::class.java.classLoader
24+
).iterator().asSequence().toList()
25+
26+
internal actual fun ensurePlatformExceptionHandlerLoaded(callback: CoroutineExceptionHandler) {
27+
// we use JVM's mechanism of ServiceLoader, so this should be a no-op on JVM.
28+
// The only thing we do is make sure that the ServiceLoader did work correctly.
29+
check(callback in platformExceptionHandlers) { "Exception handler was not found via a ServiceLoader" }
30+
}
31+
32+
internal actual fun propagateExceptionFinalResort(exception: Throwable) {
33+
// use the thread's handler
34+
val currentThread = Thread.currentThread()
35+
currentThread.uncaughtExceptionHandler.uncaughtException(currentThread, exception)
36+
}
37+
38+
// This implementation doesn't store a stacktrace, which is good because a stacktrace doesn't make sense for this.
39+
internal actual class DiagnosticCoroutineContextException actual constructor(@Transient private val context: CoroutineContext) : RuntimeException() {
40+
override fun getLocalizedMessage(): String {
41+
return context.toString()
42+
}
43+
44+
override fun fillInStackTrace(): Throwable {
45+
// Prevent Android <= 6.0 bug, #1866
46+
stackTrace = emptyArray()
47+
return this
48+
}
49+
}

kotlinx-coroutines-core/native/src/CoroutineExceptionHandlerImpl.kt

-14
This file was deleted.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/*
2+
* Copyright 2016-2022 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
3+
*/
4+
5+
package kotlinx.coroutines.internal
6+
7+
import kotlinx.coroutines.*
8+
import kotlin.coroutines.*
9+
import kotlin.native.*
10+
11+
private val lock = SynchronizedObject()
12+
13+
internal actual val platformExceptionHandlers: Collection<CoroutineExceptionHandler>
14+
get() = synchronized(lock) { platformExceptionHandlers_ }
15+
16+
private val platformExceptionHandlers_ = mutableSetOf<CoroutineExceptionHandler>()
17+
18+
internal actual fun ensurePlatformExceptionHandlerLoaded(callback: CoroutineExceptionHandler) {
19+
synchronized(lock) {
20+
platformExceptionHandlers_ += callback
21+
}
22+
}
23+
24+
@OptIn(ExperimentalStdlibApi::class)
25+
internal actual fun propagateExceptionFinalResort(exception: Throwable) {
26+
// log exception
27+
processUnhandledException(exception)
28+
}
29+
30+
internal actual class DiagnosticCoroutineContextException actual constructor(context: CoroutineContext) :
31+
RuntimeException(context.toString())

kotlinx-coroutines-test/common/src/TestScope.kt

+12
Original file line numberDiff line numberDiff line change
@@ -226,6 +226,14 @@ internal class TestScopeImpl(context: CoroutineContext) :
226226
throw IllegalStateException("Only a single call to `runTest` can be performed during one test.")
227227
entered = true
228228
check(!finished)
229+
/** the order is important: [reportException] is only guaranteed not to throw if [entered] is `true` but
230+
* [finished] is `false`.
231+
* However, we also want [uncaughtExceptions] to be queried after the callback is registered,
232+
* because the exception collector will be able to report the exceptions that arrived before this test but
233+
* after the previous one, and learning about such exceptions as soon is possible is nice. */
234+
@Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER")
235+
run { ensurePlatformExceptionHandlerLoaded(ExceptionCollector) }
236+
ExceptionCollector.addOnExceptionCallback(lock, this::reportException)
229237
uncaughtExceptions
230238
}
231239
if (exceptions.isNotEmpty()) {
@@ -239,6 +247,8 @@ internal class TestScopeImpl(context: CoroutineContext) :
239247
/** Called at the end of the test. May only be called once. Returns the list of caught unhandled exceptions. */
240248
fun leave(): List<Throwable> = synchronized(lock) {
241249
check(entered && !finished)
250+
/** After [finished] becomes `true`, it is no longer valid to have [reportException] as the callback. */
251+
ExceptionCollector.removeOnExceptionCallback(lock)
242252
finished = true
243253
uncaughtExceptions
244254
}
@@ -247,6 +257,8 @@ internal class TestScopeImpl(context: CoroutineContext) :
247257
fun legacyLeave(): List<Throwable> {
248258
val exceptions = synchronized(lock) {
249259
check(entered && !finished)
260+
/** After [finished] becomes `true`, it is no longer valid to have [reportException] as the callback. */
261+
ExceptionCollector.removeOnExceptionCallback(lock)
250262
finished = true
251263
uncaughtExceptions
252264
}

0 commit comments

Comments
 (0)