Skip to content

Commit 9099b03

Browse files
authored
Improve exception transparency: explicitly allow throwing exceptions … (#3017)
* Improve exception transparency: explicitly allow throwing exceptions from the upstream when the downstream has been failed, suppress the downstream exception by the new one, but still ignore it in the exception handling operators, that still consider the flow failed. It solves the problem of graceful shutdown: when the upstream fails unwillingly (e.g. `file.close()` has thrown in `finally` block), we cannot treat it as an exception transparency violation (hint: `finally` is a shortcut for `catch` + body that rethrows in the end), but we also cannot leave things as is, otherwise, it leads to unforeseen consequences such as successful `retry` and `catch` operators that may, or may not, then fail with an exception on an attempt to emit. Upstream exception supersedes the downstream exception only if it is not an instance of `CancellationException`, semantically emulating cancellation-friendly 'use' block. Fixes #2860
1 parent 2b1e276 commit 9099b03

File tree

5 files changed

+240
-6
lines changed

5 files changed

+240
-6
lines changed

kotlinx-coroutines-core/common/src/flow/Flow.kt

+13-4
Original file line numberDiff line numberDiff line change
@@ -131,10 +131,12 @@ import kotlin.coroutines.*
131131
*
132132
* ### Exception transparency
133133
*
134-
* Flow implementations never catch or handle exceptions that occur in downstream flows. From the implementation standpoint
135-
* it means that calls to [emit][FlowCollector.emit] and [emitAll] shall never be wrapped into
136-
* `try { ... } catch { ... }` blocks. Exception handling in flows shall be performed with
137-
* [catch][Flow.catch] operator and it is designed to only catch exceptions coming from upstream flows while passing
134+
* When `emit` or `emitAll` throws, the Flow implementations must immediately stop emitting new values and finish with an exception.
135+
* For diagnostics or application-specific purposes, the exception may be different from the one thrown by the emit operation,
136+
* suppressing the original exception as discussed below.
137+
* If there is a need to emit values after the downstream failed, please use the [catch][Flow.catch] operator.
138+
*
139+
* The [catch][Flow.catch] operator only catches upstream exceptions, but passes
138140
* all downstream exceptions. Similarly, terminal operators like [collect][Flow.collect]
139141
* throw any unhandled exceptions that occur in their code or in upstream flows, for example:
140142
*
@@ -147,6 +149,13 @@ import kotlin.coroutines.*
147149
* ```
148150
* The same reasoning can be applied to the [onCompletion] operator that is a declarative replacement for the `finally` block.
149151
*
152+
* All exception-handling Flow operators follow the principle of exception suppression:
153+
*
154+
* If the upstream flow throws an exception during its completion when the downstream exception has been thrown,
155+
* the downstream exception becomes superseded and suppressed by the upstream exception, being a semantic
156+
* equivalent of throwing from `finally` block. However, this doesn't affect the operation of the exception-handling operators,
157+
* which consider the downstream exception to be the root cause and behave as if the upstream didn't throw anything.
158+
*
150159
* Failure to adhere to the exception transparency requirement can lead to strange behaviors which make
151160
* it hard to reason about the code because an exception in the `collect { ... }` could be somehow "caught"
152161
* by an upstream flow, limiting the ability of local reasoning about the code.

kotlinx-coroutines-core/common/src/flow/operators/Errors.kt

+38-1
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,7 @@ public fun <T> Flow<T>.retryWhen(predicate: suspend FlowCollector<T>.(cause: Thr
186186
}
187187

188188
// Return exception from upstream or null
189+
@Suppress("NAME_SHADOWING")
189190
internal suspend fun <T> Flow<T>.catchImpl(
190191
collector: FlowCollector<T>
191192
): Throwable? {
@@ -200,14 +201,50 @@ internal suspend fun <T> Flow<T>.catchImpl(
200201
}
201202
}
202203
} catch (e: Throwable) {
204+
// Otherwise, smartcast is impossible
205+
val fromDownstream = fromDownstream
203206
/*
204207
* First check ensures that we catch an original exception, not one rethrown by an operator.
205208
* Seconds check ignores cancellation causes, they cannot be caught.
206209
*/
207210
if (e.isSameExceptionAs(fromDownstream) || e.isCancellationCause(coroutineContext)) {
208211
throw e // Rethrow exceptions from downstream and cancellation causes
209212
} else {
210-
return e // not from downstream
213+
/*
214+
* The exception came from the upstream [semi-] independently.
215+
* For pure failures, when the downstream functions normally, we handle the exception as intended.
216+
* But if the downstream has failed prior to or concurrently
217+
* with the upstream, we forcefully rethrow it, preserving the contextual information and ensuring that it's not lost.
218+
*/
219+
if (fromDownstream == null) {
220+
return e
221+
}
222+
/*
223+
* We consider the upstream exception as the superseding one when both upstream and downstream
224+
* fail, suppressing the downstream exception, and operating similarly to `finally` block with
225+
* the useful addition of adding the original downstream exception to suppressed ones.
226+
*
227+
* That's important for the following scenarios:
228+
* ```
229+
* flow {
230+
* val resource = ...
231+
* try {
232+
* ... emit as well ...
233+
* } finally {
234+
* resource.close() // Throws in the shutdown sequence when 'collect' already has thrown an exception
235+
* }
236+
* }.catch { } // or retry
237+
* .collect { ... }
238+
* ```
239+
* when *the downstream* throws.
240+
*/
241+
if (e is CancellationException) {
242+
fromDownstream.addSuppressed(e)
243+
throw fromDownstream
244+
} else {
245+
e.addSuppressed(fromDownstream)
246+
throw e
247+
}
211248
}
212249
}
213250
return null

kotlinx-coroutines-core/common/test/flow/operators/CatchTest.kt

+57
Original file line numberDiff line numberDiff line change
@@ -144,4 +144,61 @@ class CatchTest : TestBase() {
144144
.collect()
145145
finish(9)
146146
}
147+
148+
@Test
149+
fun testUpstreamExceptionConcurrentWithDownstream() = runTest {
150+
val flow = flow {
151+
try {
152+
expect(1)
153+
emit(1)
154+
} finally {
155+
expect(3)
156+
throw TestException()
157+
}
158+
}.catch { expectUnreached() }.onEach {
159+
expect(2)
160+
throw TestException2()
161+
}
162+
163+
assertFailsWith<TestException>(flow)
164+
finish(4)
165+
}
166+
167+
@Test
168+
fun testUpstreamExceptionConcurrentWithDownstreamCancellation() = runTest {
169+
val flow = flow {
170+
try {
171+
expect(1)
172+
emit(1)
173+
} finally {
174+
expect(3)
175+
throw TestException()
176+
}
177+
}.catch { expectUnreached() }.onEach {
178+
expect(2)
179+
throw CancellationException("")
180+
}
181+
182+
assertFailsWith<TestException>(flow)
183+
finish(4)
184+
}
185+
186+
@Test
187+
fun testUpstreamCancellationIsIgnoredWhenDownstreamFails() = runTest {
188+
val flow = flow {
189+
try {
190+
expect(1)
191+
emit(1)
192+
} finally {
193+
expect(3)
194+
throw CancellationException("")
195+
}
196+
}.catch { expectUnreached() }.onEach {
197+
expect(2)
198+
throw TestException("")
199+
}
200+
201+
assertFailsWith<TestException>(flow)
202+
finish(4)
203+
}
147204
}

kotlinx-coroutines-core/common/test/flow/operators/RetryTest.kt

+58-1
Original file line numberDiff line numberDiff line change
@@ -104,4 +104,61 @@ class RetryTest : TestBase() {
104104
job.cancelAndJoin()
105105
finish(3)
106106
}
107-
}
107+
108+
@Test
109+
fun testUpstreamExceptionConcurrentWithDownstream() = runTest {
110+
val flow = flow {
111+
try {
112+
expect(1)
113+
emit(1)
114+
} finally {
115+
expect(3)
116+
throw TestException()
117+
}
118+
}.retry { expectUnreached(); true }.onEach {
119+
expect(2)
120+
throw TestException2()
121+
}
122+
123+
assertFailsWith<TestException>(flow)
124+
finish(4)
125+
}
126+
127+
@Test
128+
fun testUpstreamExceptionConcurrentWithDownstreamCancellation() = runTest {
129+
val flow = flow {
130+
try {
131+
expect(1)
132+
emit(1)
133+
} finally {
134+
expect(3)
135+
throw TestException()
136+
}
137+
}.retry { expectUnreached(); true }.onEach {
138+
expect(2)
139+
throw CancellationException("")
140+
}
141+
142+
assertFailsWith<TestException>(flow)
143+
finish(4)
144+
}
145+
146+
@Test
147+
fun testUpstreamCancellationIsIgnoredWhenDownstreamFails() = runTest {
148+
val flow = flow {
149+
try {
150+
expect(1)
151+
emit(1)
152+
} finally {
153+
expect(3)
154+
throw CancellationException("")
155+
}
156+
}.retry { expectUnreached(); true }.onEach {
157+
expect(2)
158+
throw TestException("")
159+
}
160+
161+
assertFailsWith<TestException>(flow)
162+
finish(4)
163+
}
164+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
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.exceptions
6+
7+
import kotlinx.coroutines.*
8+
import kotlinx.coroutines.flow.*
9+
import org.junit.*
10+
import org.junit.Test
11+
import kotlin.test.*
12+
13+
class FlowSuppressionTest : TestBase() {
14+
@Test
15+
fun testSuppressionForPrimaryException() = runTest {
16+
val flow = flow {
17+
try {
18+
emit(1)
19+
} finally {
20+
throw TestException()
21+
}
22+
}.catch { expectUnreached() }.onEach { throw TestException2() }
23+
24+
try {
25+
flow.collect()
26+
} catch (e: Throwable) {
27+
assertIs<TestException>(e)
28+
assertIs<TestException2>(e.suppressed[0])
29+
}
30+
}
31+
32+
@Test
33+
fun testSuppressionForPrimaryExceptionRetry() = runTest {
34+
val flow = flow {
35+
try {
36+
emit(1)
37+
} finally {
38+
throw TestException()
39+
}
40+
}.retry { expectUnreached(); true }.onEach { throw TestException2() }
41+
42+
try {
43+
flow.collect()
44+
} catch (e: Throwable) {
45+
assertIs<TestException>(e)
46+
assertIs<TestException2>(e.suppressed[0])
47+
48+
}
49+
}
50+
51+
@Test
52+
fun testCancellationSuppression() = runTest {
53+
val flow = flow {
54+
try {
55+
expect(1)
56+
emit(1)
57+
} finally {
58+
expect(3)
59+
throw CancellationException("")
60+
}
61+
}.catch { expectUnreached() }.onEach {
62+
expect(2)
63+
throw TestException("")
64+
}
65+
66+
try {
67+
flow.collect()
68+
} catch (e: Throwable) {
69+
assertIs<TestException>(e)
70+
assertIs<CancellationException>(e.suppressed[0])
71+
}
72+
finish(4)
73+
}
74+
}

0 commit comments

Comments
 (0)