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