Skip to content

Commit b3eade1

Browse files
committed
Improve exception transparency: explicitly allow throwing exceptions from the upstream when the downstream has been failed, but also suppress such exceptions by the downstream one
It solves the problem of graceful shutdown: when the upstream fails unwillingly (e.g. file.close() has thrown in 'finally') block, we cannot treat is as an exception transparency violation (hint: 'finally' is a shortcut for 'catch'+body), 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 exception on attempt to emit. Downstream exception supersedes the upstream exception only if it is not an instance of CancellationException, semantically emulating cancellation-friendly 'use' block. Fixes #2860
1 parent 22e31b7 commit b3eade1

File tree

4 files changed

+129
-6
lines changed

4 files changed

+129
-6
lines changed

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

+14-4
Original file line numberDiff line numberDiff line change
@@ -131,10 +131,14 @@ 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+
* Flow implementations never explicitly catch and ignore exceptions that occur in downstream flows.
135+
* From the implementation standpoint, it means that `catch` blocks that wrap calls to [emit][FlowCollector.emit] and [emitAll]
136+
* are not allowed to complete normally or attempt to call [emit][FlowCollector.emit], they are only allowed
137+
* to rethrow a caught exception or throw a different exception for diagnostics or application-specific purposes.
138+
*
139+
*
140+
* Exception handling with further emission in flows shall only be performed with
141+
* [catch][Flow.catch] operator, and it is designed to only catch exceptions coming from upstream flows while passing
138142
* all downstream exceptions. Similarly, terminal operators like [collect][Flow.collect]
139143
* throw any unhandled exceptions that occur in their code or in upstream flows, for example:
140144
*
@@ -147,13 +151,19 @@ import kotlin.coroutines.*
147151
* ```
148152
* The same reasoning can be applied to the [onCompletion] operator that is a declarative replacement for the `finally` block.
149153
*
154+
* All exception-handling Flow operators follow the principle of exception suppression:
155+
*
156+
* If the upstream flow throws an exception during its completion when the downstream exception has been thrown,
157+
* the upstream exception becomes superseded and suppressed by the downstream exception.
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.
153162
*
154163
* Flow machinery enforces exception transparency at runtime and throws [IllegalStateException] on any attempt to emit a value,
155164
* if an exception has been thrown on previous attempt.
156165
*
166+
*
157167
* ### Reactive streams
158168
*
159169
* Flow is [Reactive Streams](http://www.reactive-streams.org/) compliant, you can safely interop it with

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
218+
* that it's not lost.
219+
*/
220+
if (fromDownstream == null) {
221+
return e
222+
}
223+
/*
224+
* We consider "downstream" exception as the superseding one even if the
225+
* upstream has failed (unless downstream exception is a cancellation exception, aligned with
226+
* our cancellation mechanism), so it effectively suppresses it.
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() // Unlucky throw
235+
* }
236+
* }.catch { } /* or retry */
237+
* .collect { ... }
238+
* ```
239+
* when *the downstream* throws.
240+
*/
241+
if (fromDownstream is CancellationException) {
242+
e.addSuppressed(fromDownstream)
243+
throw e
244+
} else {
245+
fromDownstream.addSuppressed(e)
246+
throw fromDownstream
247+
}
211248
}
212249
}
213250
return null

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

+38
Original file line numberDiff line numberDiff line change
@@ -144,4 +144,42 @@ 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<TestException2>(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+
}
147185
}

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

+39-1
Original file line numberDiff line numberDiff line change
@@ -104,4 +104,42 @@ 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<TestException2>(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+
}

0 commit comments

Comments
 (0)