如何在 Scala 中处理 NoSuchElementException 而不抛出异常

How to in Scala handle NoSuchElementException without throwing exception

我正在使用 Scala 的 Play 框架。我有 Postgresql 数据库。它通过以下代码获取数据:-

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 {
      }
  }
}

如果数据未绑定,则会抛出异常。这里我不想丢exception.I 想return notFound。如果不抛出异常,我什至无法编译。

如果在数据库中找不到事件,有没有办法 return notFound?

请告诉我?谢谢!

尝试:

def eventById(id: Long): Option[EventRow] = {
  val action = events.filter(_.id === id)
  val res: Future[Option[EventRow]] = db.run(action.result.headOption)
  Await.result(res, Duration.Inf)
}