https://kotlinlang.org logo
Title
s

Syex

04/15/2020, 7:12 AM
Hey, I’m working on a library that awaits some
CoroutineScope
as an input in order to
launch
some new coroutines. If any of these coroutines throw an exception it should delegate them to the initially given
CoroutineScope
. However, I figured out, if this scope has a
SupervisorJob()
all exceptions of my launched coroutines are just silently swallowed, which is probably working as intended. Is there any way I still can crash the application? I tried to create my own scope via
CoroutineScope(initialScope.coroutineContext + Job())
, but it still keeps the behavior of the supervisor job.
t

tseisel

04/15/2020, 8:00 AM
You can try setting a
CoroutineExceptionHandler
in the context of the
CoroutineScope
associated with the
SupervisorJob
:
val exceptionHandler = CoroutineExceptionHandler { exception ->
  // Do something with the caught error
}

val scope = CoroutineScope(SupervisorJob() + exceptionHandler)
Because I don't know much about coroutine exception handling (never really tried using SupervisorJob or CoroutineExceptionHandler), here is what the docs states about it: https://kotlinlang.org/docs/reference/coroutines/exception-handling.html#coroutineexceptionhandler
s

Syex

04/15/2020, 9:01 AM
The
CoroutineExceptionHandler
is never triggered this way 😕
s

streetsofboston

04/15/2020, 11:20 AM
I did some experimentation with CoroutineScopes and their exception handlers: https://link.medium.com/WPEB31h7F5
s

Syex

04/15/2020, 11:51 AM
Great article 👍 I figured out my problem arose because it threw
CancellationException
which is ignored by
CoroutineExceptionHandler
🙈
👍 1
r

rkeazor

04/15/2020, 1:26 PM
One question , if it's a library for other applications to consume. Why not just expose suspend functions with coroutine scope builder or use a flow
That way the client needs to manage the coroutineScope
s

Syex

04/15/2020, 1:29 PM
use case is a little more complex. Usage is something like “post event x, lib does some things async in a coroutine, client listens to changes on a `Flow`”
r

rkeazor

04/15/2020, 1:32 PM
So those the client give you event X than you post it ?
It still sounds possible
Have you tried this using a channelFlow?