cats-effect icon indicating copy to clipboard operation
cats-effect copied to clipboard

Dispatcher.unsafeToFuture reporting errors

Open inanme opened this issue 3 years ago • 3 comments

CE3/Dispatcher/Future/Exceptions.

I have some IOs and convert them Futures (Enforced by Play) using Dispatcher.unsafeToFuture. In certain cases I raise errors using IO.raiseError to be handled in the unsafe region. The issue is that I see unwanted stacktraces in the console for these potentially expected errors printed by CE runtime(WorkStealingThreadPool) as they are rightfully considered as unhandled errors.

The following example may produce the case where an exception will be printed

package example

import cats.effect.{ IO, IOApp }
import cats.effect.std.{ Dispatcher, Queue }
import cats.effect.unsafe.implicits.global

import scala.concurrent.duration._
import scala.concurrent.{ Await, ExecutionContext, Future }
import scala.util.control.NoStackTrace

object MainDispatcher {

  val (dispatcher, dispatcherShutdown) = Dispatcher[IO].allocated.unsafeRunSync()

  def main(args: Array[String]): Unit = {
    case class SomeError(message: String) extends NoStackTrace
    val m: Future[Unit] =
      dispatcher
        .unsafeToFuture(IO.raiseError(SomeError("nice")))
        .recover {
          case SomeError(message) =>
            println(message)
            ()
        }(ExecutionContext.global)

    Await.result(m, 10.seconds)
  }

}

inanme avatar Aug 25 '22 17:08 inanme

Thanks for the report. What is your version of Cats Effect?

armanbilge avatar Aug 25 '22 17:08 armanbilge

Thanks for looking at this, it is 3.3.14.

inanme avatar Aug 25 '22 17:08 inanme

As a workaround you can do something like this:

 dispatcher
  .unsafeToFuture(myIO.attempt)
  .flatMap {
    case Left(ex) => Future.failed(ex)
    case Right(result) => Future.successful(result)
  }

This is most likely due to https://github.com/typelevel/cats-effect/pull/2868. I'm not sure if this should count as an unhandled error, since it is being reported to the Future and thus should be handled there. It seems like we should be able to fix this.

armanbilge avatar Aug 25 '22 17:08 armanbilge

I'd like to investigate this one, cc @armanbilge :D

samspills avatar Mar 06 '23 23:03 samspills

I think this was fixed in https://github.com/typelevel/cats-effect/pull/3487 :)

armanbilge avatar Jan 11 '24 22:01 armanbilge