我一直使用的在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)
案例,我会收到一条警告,说我的模式匹配将失败,但是必须匹配我知道我不应该捕捉的东西是很乏味的。有没有更好的方法来处理成功和适当的失败?