I have an async coroutine, that might throw an exception. How can I propagate the exception to my CoroutineExceptionHandler? With try/catch around await I'm able to catch the exception, but I can't seem to propagate the handling to the handler, no matter the context:
val handler = CoroutineExceptionHandler { _, e -> e.printStackTrace() }
val context = Executors.newSingleThreadExecutor().asCoroutineDispatcher() + handler
val scope = CoroutineScope(context)
val async = scope.async {
throw Exception("Test exception")
}
runBlocking {
try {
async.await()
} catch (e: Exception) {
log.error("Exception thrown", e)
}
delay(1_000)
}
I've tried rethrowing the exception from the catch, or wrapping it with some of the following constructs:
catch (e: Exception) {
throw e
// withContext(context) { throw e }
// scope.launch { throw e }
// supervisorScope { throw e }
}
Sadly, none of them propagated it to the handler. Can I somehow utilize CoroutineExceptionHandler with async coroutines?