scala - Akka future 异常(exception)

标签 scala exception akka future

当 future 的参与者抛出异常时会发生什么?

根据 Akka 文档 http://doc.akka.io/docs/akka/snapshot/scala/futures.html :

It doesn't matter if an Actor or the dispatcher is completing the Future, if an Exception is caught the Future will contain it instead of a valid result. If a Future does contain an Exception, calling Await.result will cause it to be thrown again so it can be handled properly.

我不确定这就是我在运行这段代码时所看到的:

  class Worker extends Actor {
    def receive = {
      case i: Int => throw new RuntimeException
    }         
  }

  implicit val system = ActorSystem("MySystem")
  val worker = system.actorOf(Props(new Worker), name="worker")
  implicit val timeout = Timeout(5 minutes)
  val future = worker ? 0
  val res = Await.result(future, 10 seconds)

根据文档,Await.result应该再次抛出异常,但我得到的是TimeoutException!有人可以澄清一下吗?

最佳答案

对于 Actor ,您需要捕获异常并 return it as a failure status 。现在您没有向发件人返回任何内容,因此您遇到了超时异常:

class Worker extends Actor {
  def receive = {
    case i: Int => {
      try {
        throw new RuntimeException
        sender ! "Some good result"
      } catch {
        case e: Exception =>
          sender ! akka.actor.Status.Failure(e) // Alert the sender of the failure
          throw e // Alert any supervisor actor of the failure
      }
    }
  }
}

Futures 可以更优雅地处理这个问题,因为它们总是发送结果,而 actor 则不会(这会给你与上面相同的结果):

  val future = Future {
    throw new RuntimeException
  }

关于scala - Akka future 异常(exception),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16095462/

相关文章:

Java 异常,捕捉什么,不捕捉什么?

scala - 使用Akka Play 2.5-找不到参数超时的隐式值: akka. util.Timeout

scala - 如果抛出异常,Akka Actor 不会终止

Scala 模式匹配打印精美

postgresql - 使用 Anorm 在 PostgreSQL 中插入图像文件

java - 错误: Integers added together in successive uses of scanner class

c# - 导致 TPL 数据流管道死锁的异常

scala - 固定大小和元素边界的 Nat 列表

scala - 如何在启动时打印 akka 配置?

java - 将参数注入(inject) Akka Props 和 Creator 实例