2015-05-21 77 views
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?

请让我知道吗?谢谢!

+1

只需使用'headOption',而不是'head',然后检查它的一些或无。 –

回答

0

尝试:

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) 
} 
相关问题