How can I handle exception throwing in bg task aft...
# coroutines
p
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
IIRC, you can apply an exception handler, which will get called instead of exploding to the surface
p
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
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
oops, sorry my code works both for
run
and
launch
, didn’t put it initially in the right function. So problem solved, thanks!
👍 1