1 package kotlinx.coroutines
2
3 import kotlinx.coroutines.internal.*
4 import kotlin.coroutines.*
5
6 /**
7 * Helper function for coroutine builder implementations to handle uncaught and unexpected exceptions in coroutines,
8 * that could not be otherwise handled in a normal way through structured concurrency, saving them to a future, and
9 * cannot be rethrown. This is a last resort handler to prevent lost exceptions.
10 *
11 * If there is [CoroutineExceptionHandler] in the context, then it is used. If it throws an exception during handling
12 * or is absent, all instances of [CoroutineExceptionHandler] found via [ServiceLoader] and
13 * [Thread.uncaughtExceptionHandler] are invoked.
14 *
15 * @suppress **This is internal API and it is subject to change.**
16 */
17 @InternalCoroutinesApi
handleCoroutineExceptionnull18 public fun handleCoroutineException(context: CoroutineContext, exception: Throwable) {
19 val reportException = if (exception is DispatchException) exception.cause else exception
20 // Invoke an exception handler from the context if present
21 try {
22 context[CoroutineExceptionHandler]?.let {
23 it.handleException(context, reportException)
24 return
25 }
26 } catch (t: Throwable) {
27 handleUncaughtCoroutineException(context, handlerException(reportException, t))
28 return
29 }
30 // If a handler is not present in the context or an exception was thrown, fallback to the global handler
31 handleUncaughtCoroutineException(context, reportException)
32 }
33
handlerExceptionnull34 internal fun handlerException(originalException: Throwable, thrownException: Throwable): Throwable {
35 if (originalException === thrownException) return originalException
36 return RuntimeException("Exception while trying to handle coroutine exception", thrownException).apply {
37 addSuppressed(originalException)
38 }
39 }
40
41 /**
42 * Creates a [CoroutineExceptionHandler] instance.
43 * @param handler a function which handles exception thrown by a coroutine
44 */
45 @Suppress("FunctionName")
CoroutineExceptionHandlernull46 public inline fun CoroutineExceptionHandler(crossinline handler: (CoroutineContext, Throwable) -> Unit): CoroutineExceptionHandler =
47 object : AbstractCoroutineContextElement(CoroutineExceptionHandler), CoroutineExceptionHandler {
48 override fun handleException(context: CoroutineContext, exception: Throwable) =
49 handler.invoke(context, exception)
50 }
51
52 /**
53 * An optional element in the coroutine context to handle **uncaught** exceptions.
54 *
55 * Normally, uncaught exceptions can only result from _root_ coroutines created using the [launch][CoroutineScope.launch] builder.
56 * All _children_ coroutines (coroutines created in the context of another [Job]) delegate handling of their
57 * exceptions to their parent coroutine, which also delegates to the parent, and so on until the root,
58 * so the `CoroutineExceptionHandler` installed in their context is never used.
59 * Coroutines running with [SupervisorJob] do not propagate exceptions to their parent and are treated like root coroutines.
60 * A coroutine that was created using [async][CoroutineScope.async] always catches all its exceptions and represents them
61 * in the resulting [Deferred] object, so it cannot result in uncaught exceptions.
62 *
63 * ### Handling coroutine exceptions
64 *
65 * `CoroutineExceptionHandler` is a last-resort mechanism for global "catch all" behavior.
66 * You cannot recover from the exception in the `CoroutineExceptionHandler`. The coroutine had already completed
67 * with the corresponding exception when the handler is called. Normally, the handler is used to
68 * log the exception, show some kind of error message, terminate, and/or restart the application.
69 *
70 * If you need to handle exception in a specific part of the code, it is recommended to use `try`/`catch` around
71 * the corresponding code inside your coroutine. This way you can prevent completion of the coroutine
72 * with the exception (exception is now _caught_), retry the operation, and/or take other arbitrary actions:
73 *
74 * ```
75 * scope.launch { // launch child coroutine in a scope
76 * try {
77 * // do something
78 * } catch (e: Throwable) {
79 * // handle exception
80 * }
81 * }
82 * ```
83 *
84 * ### Uncaught exceptions with no handler
85 *
86 * When no handler is installed, exception are handled in the following way:
87 * - If exception is [CancellationException], it is ignored, as these exceptions are used to cancel coroutines.
88 * - Otherwise, if there is a [Job] in the context, then [Job.cancel] is invoked.
89 * - Otherwise, as a last resort, the exception is processed in a platform-specific manner:
90 * - On JVM, all instances of [CoroutineExceptionHandler] found via [ServiceLoader], as well as
91 * the current thread's [Thread.uncaughtExceptionHandler], are invoked.
92 * - On Native, the whole application crashes with the exception.
93 * - On JS, the exception is logged via the Console API.
94 *
95 * [CoroutineExceptionHandler] can be invoked from an arbitrary thread.
96 */
97 public interface CoroutineExceptionHandler : CoroutineContext.Element {
98 /**
99 * Key for [CoroutineExceptionHandler] instance in the coroutine context.
100 */
101 public companion object Key : CoroutineContext.Key<CoroutineExceptionHandler>
102
103 /**
104 * Handles uncaught [exception] in the given [context]. It is invoked
105 * if coroutine has an uncaught exception.
106 */
handleExceptionnull107 public fun handleException(context: CoroutineContext, exception: Throwable)
108 }
109