0

我一直使用的在Akka内部处理Future完成的模式看起来像这样:

val caller = sender()
doSomethingAsync().onComplete {
  case Success(arg) => caller ! SuccessMsg(arg)
  case Failure(e:Exception) => caller ! FailureMsg()
  case Failure(e) => throw e // so as to not catch a non-exception Throwable
}

我知道我更喜欢map未来而不是使用onComplete,但是混合Future消息传递语义会导致你最终进入一个副作用操作的地方。

如果我不考虑这个Failure(e)案例,我会收到一条警告,说我的模式匹配将失败,但是必须匹配我知道我不应该捕捉的东西是很乏味的。有没有更好的方法来处理成功和适当的失败?

4

1 回答 1

4

您可以使用从 a向 ActorpipeTo发送消息。Future你可以结合它Future.recover来处理这个Failure案子。

import akka.pattern.pipe

doSomethingAsync()
  .map(SuccessMsg)
  .recover{ case e: Exception => FailureMsg() }
  .pipeTo(caller)
于 2015-10-07T00:15:54.370 回答