https://kotlinlang.org logo
#coroutines
Title
# coroutines
p

pilgr

07/26/2017, 12:25 PM
How can I handle exception throwing in bg task after Kotlin coroutine is canceled? For now, this leads to app crash. https://stackoverflow.com/questions/45326818/cant-catch-exception-throwing-after-kotlin-coroutine-is-cancelled
k

kingsley

07/26/2017, 12:30 PM
IIRC, you can apply an exception handler, which will get called instead of exploding to the surface
p

pilgr

07/26/2017, 1:12 PM
Thank, I’m trying to add handler to
run
or
launch
, still have a crash.
Copy code
run(CommonPool + CoroutineExceptionHandler({ _, e ->
               Log.e("TAG", "CoroutineExceptionHandler", e)
            }))
k

kingsley

07/26/2017, 1:22 PM
You should define the exception handler this way:
Copy code
object ExceptionHandler :
            AbstractCoroutineContextElement(CoroutineExceptionHandler),
            CoroutineExceptionHandler {
        override fun handleException(context: CoroutineContext, exception: Throwable) {
            Log.e(exception)
        }
    }
Then use it like:
Copy code
launch(UI + ExceptionHandler) {
 ...
}
p

pilgr

07/26/2017, 1:42 PM
oops, sorry my code works both for
run
and
launch
, didn’t put it initially in the right function. So problem solved, thanks!
👍 1
3 Views