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

How to send requirement failed exception back to sender?

我有这段代码:

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 的发送者。

最好的方法是什么?

您的代码无法正常工作,并且与您的评论不符。条件的第一条路径不提供 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)
}