Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know which Future fail when doing Future.sequence?

Tags:

scala

akka

Here is an example receive part of an actor I'm working on:

def receive = {
        case "begin" =>
            val listOfFutures: IndexedSeq[Future[Any]] = workers.map(worker => worker ? Work("test"))
            val future: Future[IndexedSeq[Any]] = Future.sequence(listOfFutures)

            future onComplete {
                case Success(result) => println("Eventual result: "+result)
                case Failure(ex) =>  println("Failure: "+ex.getMessage)
            }
        case msg => println("A message received: "+msg)
    }

When ask fails for one of the workers (in case of a timeout), sequence future completes with failure. However I want to know which worker(s) have failed. Is there a more elegant way rather than simply mapping listOfFutures one by one without using Future.sequence ?

like image 786
Ömer Faruk Gül Avatar asked Jan 08 '23 14:01

Ömer Faruk Gül


2 Answers

You can use the future's recover method to map or wrap the underlying exception:

import scala.concurrent.{Future, ExecutionContext}

case class WorkerFailed(name: String, cause: Throwable) 
  extends Exception(s"$name - ${cause.getMessage}", cause)

def mark[A](name: String, f: Future[A]): Future[A] = f.recover {
  case ex => throw WorkerFailed(name, ex)
}

import ExecutionContext.Implicits.global

val f = (0 to 10).map(i => mark(s"i = $i", Future { i / i }))
val g = Future.sequence(f)

g.value  // WorkerFailed: i = 0 - / by zero
like image 137
0__ Avatar answered Jan 22 '23 11:01

0__


Thanks to @O__ I have come with another solution that may a better fit some some cases.

case class WorkerDone(name: String)
case class WorkerFailed(name: String)

import ExecutionContext.Implicits.global

val f = (0 to 10).map {
    i => Future {i/i; WorkerDone(s"worker$i")}.recover{
        case ex => WorkerFailed(s"worker$i")
    }
}
val futureSeq = Future.sequence(f)

futureSeq onComplete {
        case Success(list) => list.collect {case result:WorkerFailed => result}.foreach {failed => println("Failed: "+failed.name)}
        case Failure(ex) => println("Exception: "+ex.getMessage)
    }

// just to make sure program doesn't end before onComplete is called.
Thread.sleep(2000L)

I'm not sure that if my example is a good practice, but my aim is to know which workers did fail no matter how did they fail.

like image 40
Ömer Faruk Gül Avatar answered Jan 22 '23 12:01

Ömer Faruk Gül