如果Future调用失败,则失败一个actor

时间:2017-02-08 15:38:22

标签: scala akka

我正在执行未来通话中的某些事情。如果将来的调用失败,我会在成功完成时将结果返回给发送者,或者使actor失败。这将由父母处理,其中实施了具有监督策略的RoundRobinPool。

以下是代码段。

private def getData(sender: ActorRef): Unit = {

    dao.getData().mapTo[List[Data]].map(result => sender ! result)
      .onFailure {
        case e: NullPointerExcetpion => {
          println("+++++++ Throwing exception")
      // throwning the exception from here doesn't cause the supervisor to restart this actor
          throw t
        }
      }

      // throwing the exception from here makes the supervisor strategy to take action
      throw new NullPointerExcetpion

  }

如果未来返回异常,我们如何让演员失败?

干杯,

UTSAV

1 个答案:

答案 0 :(得分:1)

问题是onFailure回调是从任意线程抛出的,而不是运行actor的那个。你可以做的是将结果传递给自己,然后抛出:

case class MyFailure(e: Throwable)

def receive: {
  case MyFailure(e) => throw e
}

private def getData(sender: ActorRef): Unit = {
  dao
   .getData()
   .mapTo[List[Data]]
   .recover {
     case e => MyFailure(e)
   }
   .pipeTo(self)
}

或者@jrudolph建议:

def receive: {
  case Status.Failure(e) => throw e
}

private def getData(sender: ActorRef): Unit = {
  dao
   .getData()
   .mapTo[List[Data]]
   .pipeTo(self)
}