import io.kotlintest.specs.StringSpec import kotlinx.coroutines.* import java.util.* import kotlin.coroutines.AbstractCoroutineContextElement import kotlin.coroutines.CoroutineContext import kotlin.coroutines.resume class RequestContext() : AbstractCoroutineContextElement(Key) { companion object Key : CoroutineContext.Key val stack = Stack() } suspend fun addHumanStack(msg: String): Unit = suspendCancellableCoroutine { cont -> cont.context[RequestContext]!!.stack.push(msg) cont.resume(Unit) } suspend fun getHumanStack(): Iterable = suspendCancellableCoroutine { cont -> val a = cont.context[RequestContext]!!.stack.asIterable() cont.resume(a) } class RequestContextTest : StringSpec({ "human stack context at multiple scope levels" { val requestContext = RequestContext() // let's create one per http request at handler (basically entrypoint) runBlocking(requestContext) { try { addHumanStack("Processing shit") withContext(Dispatchers.IO) { addHumanStack("Fetching record 1 from database record 1") coroutineScope { addHumanStack("Deserialzing jsonb payload") throw Exception("ah shit this aint valid json") } } } catch (e: Exception) { val humanStack = getHumanStack() println("Exception occured at ${humanStack.toList().joinToString(" -> ")} : $e") } } } })