https://kotlinlang.org logo
Title
p

Patrick Steiger

03/16/2023, 12:15 AM
Wondering what would be the idiomatic way to launch multiple coroutines in a
supervisorScope
while still capturing all exceptions (aggregated) that are thrown in them. Note that I do not want failure of a child to cancel other children (or the scope), hence supervisor scope, but I might want to “sum” (probably
addSuppressed
) all exceptions and throw it later after scope is done Right now I’m using
withContext
with a custom
CoroutineExceptionHandler
that puts all exceptions in a collection and later reduce the collection and throw, but it just feels boilerplate-y and wonder if I’m missing something
s

Sam

03/16/2023, 1:24 PM
How would you write this if you weren’t using coroutines? Maybe instead of having the child coroutines fail, you could instead have them return something like a
Result
.
p

Patrick Steiger

03/16/2023, 3:49 PM
I think adding the
async
to a list and then
mapNotNull { runCatching { it.await() }.exceptionOrNull() }
is indeed cleaner, then I can return a list of
Throwable
to join and throw later
k

kevin.cianfarini

03/16/2023, 8:30 PM
don’t use
runCatching
in coroutines code. It can capture
CancellationException
and break structured concurrency. See: https://github.com/Kotlin/kotlinx.coroutines/issues/1814