问题
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