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