如何将需求失败的异常发送回发件人?

时间:2015-01-04 16:28:20

标签: scala akka

我有这段代码:

override def create(policy: Policy): Future[Policy] = {
  //require that an id has not been assigned to this policy

  if (policy.id != None) { 
    //ugly and does not type check, but trying to convey the general idea 
    sender ! require(policy.id == None) 
    require(policy.id == None)
  else { 
    Future {
      policy //dummy code for simplicity sake
    }
  } 
}

我想向发件人发送一条消息,说明没有满足要求。我想尝试尽可能以最惯用的方式做到这一点。我希望理想地终止此actor中的执行并将需求消息发送回此actor的发送者。

这样做的最佳方式是什么?

1 个答案:

答案 0 :(得分:1)

您所拥有的代码并非构建起来,而且与您的评论不符。条件的第一个路径不提供Future[Policy],也不应该提供receive()。如果从case class PolicyResult(reason: String) override def create(policy: Policy): Future[Policy] = Future(policy) def receive: { case p: Policy if p.id == None => sender ! PolicyResult("Policy must have id defined") case p: Policy => ... val vp = create(p) } 方法调用此方法,则需要重构以便及早识别失败。

{{1}}