1
votes

How can I print current stack trace inside a suspending function?

If I try the usual way:

    suspend fun f() {
        Exception().printStackTrace()
    }

It will print something like:

java.lang.Exception
    at car2share.sync.reservations.ReservationLogWriter.write(ReservationLogWriter.kt:105)
    at car2share.sync.reservations.ReservationLogWriter$write$2.invokeSuspend(ReservationLogWriter.kt)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    at kotlinx.coroutines.DispatchedTask.run(Dispatched.kt:241)
    at kotlinx.coroutines.EventLoopImplBase.processNextEvent(EventLoop.common.kt:270)
    at kotlinx.coroutines.BlockingCoroutine.joinBlocking(Builders.kt:79)
    at kotlinx.coroutines.BuildersKt__BuildersKt.runBlocking(Builders.kt:54)
    at kotlinx.coroutines.BuildersKt.runBlocking(Unknown Source)
    at kotlinx.coroutines.BuildersKt__BuildersKt.runBlocking$default(Builders.kt:36)
    at kotlinx.coroutines.BuildersKt.runBlocking$default(Unknown Source)

Which does not contain the full stack trace.

2
For me it does. Please provide a stackoverflow.com/help/minimal-reproducible-example. Out of curiosity, what code do you have at ReservationLogWriter.kt:105 ? Also please clarify what you mean with "full stack trace". Maybe that's where our definitions diverge. - Enselic

2 Answers

1
votes

Try setting this option:

System.setProperty(
    kotlinx.coroutines.DEBUG_PROPERTY_NAME,
    kotlinx.coroutines.DEBUG_PROPERTY_VALUE_ON
)

This enables the coroutine debug mode, which recovers the full stacktraces. See more here: https://github.com/Kotlin/kotlinx.coroutines/blob/master/docs/debugging.md

0
votes

You can try throwing an exception in suspending function :

suspend fun f() {
   kotlin.runCatching {
     //any code that can throw an exception
     throw Exception()
     }.onFailure {
     //print stack trace
     it.printStackTrace()
  }
}