Skip to content

Instantly share code, notes, and snippets.

@samspills
Created March 7, 2023 02:59
Show Gist options
  • Save samspills/9641ffe0b76938b14a9721034a1fe7fb to your computer and use it in GitHub Desktop.
Save samspills/9641ffe0b76938b14a9721034a1fe7fb to your computer and use it in GitHub Desktop.
CE 3131 example (maybe)
import cats.effect.std.Dispatcher
import scala.concurrent.duration._
import scala.concurrent.{Await, ExecutionContext, Future}
import cats.effect.unsafe.implicits.global
object StackTraceExample {
case class SomeError(message: String) extends Exception
val (dispatcher, dispatcherShutdown) = Dispatcher.parallel[IO].allocated.unsafeRunSync()
def main(args: Array[String]): Unit = {
val m: Future[Unit] =
dispatcher
.unsafeToFuture(IO.raiseError(SomeError("nice")))
.recover {
case SomeError(message) =>
println(s"recovered from exception: $message")
()
}(ExecutionContext.global)
Await.result(m, 10.seconds)
}
}
object NoTraceExample {
case class SomeError(message: String) extends Exception
val (dispatcher, dispatcherShutdown) = Dispatcher.sequential[IO].allocated.unsafeRunSync()
def main(args: Array[String]): Unit = {
val m: Future[Unit] =
dispatcher
.unsafeToFuture(IO.raiseError(SomeError("nice")))
.recover {
case SomeError(message) =>
println(s"recovered from exception: $message")
()
}(ExecutionContext.global)
Await.result(m, 10.seconds)
}
}

The stack trace example prints the recovery message AND the original exception

sbt:cats-effect> exampleJVM/runMain cats.effect.example.StackTraceExample
[info] running cats.effect.example.StackTraceExample
recovered from exception: nice
cats.effect.example.BrokenExample$SomeError
[success] Total time: 0 s, completed Mar. 6, 2023, 9:40:57 p.m.

The no trace example prints only the recovery message

sbt:cats-effect> exampleJVM/runMain cats.effect.example.NoTraceExample
[info] running cats.effect.example.NoTraceExample
recovered from exception: nice
[success] Total time: 2 s, completed Mar. 6, 2023, 9:40:52 p.m.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment