Catch Unique Key Exception Scala Slick

*爱你&永不变心* 提交于 2019-12-12 04:23:32

问题


Below is the code I use in inserting into the db however when the name of a group which is unique is entered I get a unique key violation in the logs

override def create(groups: GroupEntity): Future[GroupEntity] = db.run{groupsTableQuery returning groupsTableQuery += groups}

回答1:


Recover using recoverWith. As all exceptions will be of type PSQLException, check if certain keywords exist in message of the exception to handle it.

val future = db.run { groupsTableQuery returning groupsTableQuery += groups }

future.recoverWith { 
 case ex: PSQLException =>
   val msg = ex.getMessage
   //check message for keywords for specific errors
   Future.successful(0)
 case ex => Future.failed(ex)
}



回答2:


Thanks for the update however I found a simpler way to solve the problem and this was solved in my route. below is the solution

val saved : Future[GroupEntity] = groupRepositoryImpl.create(group) 
onComplete(saved){
case Success(value) => complete(saved.map(_.toJson))
case Failure(ex)    => complete((InternalServerError, s"An error occurred: ${ex.getMessage}"))}

result => An error occurred: ERROR: duplicate key value violates unique constraint "groups_name_key_name " Detail: Key (groups_name)=(Test Shop) already exists.



来源:https://stackoverflow.com/questions/42253816/catch-unique-key-exception-scala-slick

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!