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',然後檢查它的一些或無。 –