0
我使用播放框架由斯卡拉。我有Postgresql数据库。它通过以下代码提取数据: -如何在斯卡拉处理NoSuchElementException异常没有抛出异常
def eventById(id: Long): Option[EventRow] = {
val action = events.filter(_.id === id)
val results = db.run(action.result.head)
val notFound = None: Option[EventRow]
try {
Some(Await.result(results, Duration.Inf))
} catch {
case e: Exception => Logger.info(s"Failed to fetch event by id: $e.")
notFound
} finally {
}
}
}
这里万一数据未绑定,则会引发异常。这里我不想抛出异常,我想返回notFound。如果不抛出异常,我甚至不能编译。
如果在数据库中找不到事件,有没有办法返回notFound?
请让我知道吗?谢谢!
只需使用'headOption',而不是'head',然后检查它的一些或无。 –