恢复未来未如预期那样做出响应(标量)

时间:2018-08-24 00:38:45

标签: scala playframework

我有一个自定义案例类异常:

 case class RecordNotFoundException(msg: String) extends RuntimeException(msg)

在我的dao中,我有一个方法可以从数据库中提取对象,该方法返回将来,如果将来失败,我将抛出RecordNotFoundException异常:

  def getPerson(personId: String): Future[Person] = {
    val q = quote {
      query[Person].filter(per => per.personId == lift(personId))
    }
    ctx.run.map(_.head) recover {
      case ex: NoSuchElementException => throw RecordNotFoundException(s"personId $personId does not exist")
    }
  }

在另一个方法中,我将其称为getPerson方法,因此我在该另一个方法中添加了恢复功能,当将来由于RecordNotFoundException而失败时,我想返回一些内容:

def run(personDao: PersonDao): Future[String] = {
  if (true) {
    for {
      person <- personDao.getPerson("some_user_id")
      something <- someOtherFuture
    } yield {
      // what happens here not relevant
    }
  } else {
    Future.successful("got to the else")
  } recover {
    case e: RecordNotFoundException => "got to the recover"
  }
}

所以基本上我希望当getPerson失败时,run()方法将返回“ got to the recovery”,但是由于某种原因,我无法恢复到该故障...故障将返回到控制器。

有人知道为什么吗?

1 个答案:

答案 0 :(得分:1)

首先查看您的recover在哪里。为什么不将其移至方法的最后一行?像这样:

def getPerson(id: String): Future[String] = Future("Andy")
def someOtherFuture(id: String) = Future("Mandy")

case class RecordNotFoundException(msg: String) extends RuntimeException(msg)

def run(personDao: String): Future[String] = {
  if (true) 
    for {
      person <- getPerson("some_user_id")
      something <- someOtherFuture("1")
    } yield {
      person
    }
  else Future.successful("got to the else")
}recover { case e: RecordNotFoundException => "got to the recover"}

也将recover的{​​{1}}移动。

我认为在模型和/或服务中使用getPerson并没有错,然后异常又回到了控制器。然后,控制器方法处理自定义的异常;并将Future/recoverInternalServerError返回给用户或API调用。

相关问题