vicaba
vicaba

Reputation: 2876

Scala catch thrown errors by a sequence of futures

Is it possible to asynchronously catch all errors given a list of futures?

I was thinking of something like:

Future { throw Exception } zip Future { throw Exception } recover ...

But I only receive a Throwable in the recover part. Any idea?

Upvotes: 2

Views: 281

Answers (1)

Rob Starling
Rob Starling

Reputation: 3908

zip's docs clearly say it prefers errors from this over those from that (my emphasis):

def zip[U](that: Future[U]): Future[(T, U)] Zips the values of this and that future, and creates a new future holding the tuple of their results.

If this future fails, the resulting future is failed with the throwable stored in this. Otherwise, if that future fails, the resulting future is failed with the throwable stored in that.

You could implement your own function to combine two futures into Future[(Try[T], Try[U])], like:

def zipToTry[T,U](a: Future[T], b: Future[U])
                 (implicit executor: ExecutionContext)
    : Future[(Try[T], Try[U])] = {

  val t: Try[T] = a.map { Success(_) }.recover { Failure(_) }
  val u: Try[U] = b.map { Success(_) }.recover { Failure(_) }
  t.zip(u)
}

(i haven't tested this, but you get the idea)

Upvotes: 3

Related Questions