1 /*
2  * Copyright 2016-2018 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 /**
8  * This exception gets thrown if an exception is caught while processing [CompletionHandler] invocation for [Job].
9  *
10  * @suppress **This an internal API and should not be used from general code.**
11  */
12 @InternalCoroutinesApi
13 public actual class CompletionHandlerException public actual constructor(
14     message: String,
15     public override val cause: Throwable
16 ) : RuntimeException(message.withCause(cause))
17 
18 /**
19  * Thrown by cancellable suspending functions if the [Job] of the coroutine is cancelled while it is suspending.
20  * It indicates _normal_ cancellation of a coroutine.
21  * **It is not printed to console/log by default uncaught exception handler**.
22  * (see [CoroutineExceptionHandler]).
23  */
24 public actual open class CancellationException actual constructor(message: String?) : IllegalStateException(message)
25 
26 /**
27  * Creates a cancellation exception with a specified message and [cause].
28  */
29 @Suppress("FunctionName")
30 public actual fun CancellationException(message: String?, cause: Throwable?) : CancellationException =
31     CancellationException(message.withCause(cause))
32 
33 /**
34  * Thrown by cancellable suspending functions if the [Job] of the coroutine is cancelled or completed
35  * without cause, or with a cause or exception that is not [CancellationException]
36  * (see [Job.getCancellationException]).
37  */
38 internal actual class JobCancellationException public actual constructor(
39     message: String,
40     public override val cause: Throwable?,
41     internal actual val job: Job
42 ) : CancellationException(message.withCause(cause)) {
43     override fun toString(): String = "${super.toString()}; job=$job"
44     override fun equals(other: Any?): Boolean =
45         other === this ||
46             other is JobCancellationException && other.message == message && other.job == job && other.cause == cause
47     override fun hashCode(): Int =
48         (message!!.hashCode() * 31 + job.hashCode()) * 31 + (cause?.hashCode() ?: 0)
49 }
50 
51 @Suppress("FunctionName")
52 internal fun IllegalStateException(message: String, cause: Throwable?) =
53     IllegalStateException(message.withCause(cause))
54 
55 private fun String?.withCause(cause: Throwable?) =
56     when {
57         cause == null -> this
58         this == null -> "caused by $cause"
59         else -> "$this; caused by $cause"
60     }
61 
62 @Suppress("NOTHING_TO_INLINE")
63 internal actual inline fun Throwable.addSuppressedThrowable(other: Throwable) { /* empty */ }
64 
65 // For use in tests
66 internal actual val RECOVER_STACK_TRACES: Boolean = false
67