2

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?

vicaba
  • 2,836
  • 1
  • 27
  • 45
  • 1
    Can you add a recover to both `Future`'s before zipping them? – Pim Verkerk Apr 06 '16 at 15:39
  • I'm showing a simplified example. That's what I actually did, but the thing is that I want to combine the exceptions thrown by all the futures that have failed. – vicaba Apr 06 '16 at 15:41

1 Answers1

3

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)

Rob Starling
  • 3,868
  • 3
  • 23
  • 40