My table has a unique index on a pair of columns in my postgresql database.
I want to know how I can catch a duplicate key exception when I am inserting:
<
In Slick 3.x you can use asTry.
I'm using MySQL, but the same code can be used for PostgreSQL, only the exceptions are different.
import scala.util.Try
import scala.util.Success
import scala.util.Failure
db.run(myAction.asTry).map {result =>
result match {
case Success(res) =>
println("success")
// ...
case Failure(e: MySQLIntegrityConstraintViolationException) => {
//code: 1062, status: 23000, e: Duplicate entry 'foo' for key 'name'
println(s"MySQLIntegrityConstraintViolationException, code: ${e.getErrorCode}, sql status: ${e.getSQLState}, message: ${e.getMessage}")
// ...
}
case Failure(e) => {
println(s"Exception in insertOrUpdateListItem, ${e.getMessage}")
// ...
}
}
}
Note: It's also possible to map the action (myAction.asTry.map ...) instead of the future returned by db.run.