【发布时间】:2018-08-24 00:38:45
【问题描述】:
我有一个自定义案例类异常:
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"
}
}
所以基本上我希望 run() 方法在 getPerson 失败时返回“得到恢复”,但由于某种原因我没有得到恢复……失败回到控制器。
请问有人知道这是为什么吗?
【问题讨论】:
-
recover 不应该抛出,它应该返回一个值。也许你想要 recoverWith。
标签: scala playframework