Justinas Simanavicius
Justinas Simanavicius

Reputation: 358

How to restart stack trace when rethrowing an exception?

Is there a way to restart stack trace given a caught exception? Problem is that when I await a future and it fails, stack trace does not tell which await failed.

For example, stack trace tells that doSomethingMayFail failed:

def doSomethingMayFail() = Future { throw new RuntimeException("test") }
Await.result(doSomethingMayFail(), 1.seconds)
Await.result(doSomethingMayFail(), 1.seconds)
java.lang.RuntimeException: test
    at RandomSpec$$anon$7.$anonfun$doSomethingThatFails$1(RandomSpec.scala:79)
    at scala.concurrent.Future$.$anonfun$apply$1(Future.scala:672)
    at scala.concurrent.impl.Promise$Transformation.run(Promise.scala:431)
    at java.base/java.util.concurrent.ForkJoinTask$RunnableExecuteAction.exec(ForkJoinTask.java:1426)
    at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:290)
    at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(ForkJoinPool.java:1020)
    at java.base/java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1656)
    at java.base/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1594)
    at java.base/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:183)

Upvotes: 0

Views: 187

Answers (1)

Justinas Simanavicius
Justinas Simanavicius

Reputation: 358

One way to is to catch, fillInStackTrace and rethrow the exception.

try {
  Await.result(doSomethingThatFails(), 1.seconds)
} catch {
  e => throw e.fillInStackTrace()
}

Upvotes: 1

Related Questions