I have a registration Action that asks for user emails, in my postgres database I only allow unique emails. When I put in a duplicate email I get back the error message
**Failure(org.postgresql.util.PSQLException: ERROR: duplicate key value violates
unique constraint "same_name_profiles_email"
Detail: Key (email)=([email protected]) already exists.)**
I would like to return my own generic error message instead, something similar to what they are doing here How to catch slick postgres exceptions for duplicate key value violations . The issue I am facing is that I am getting an error of
**constructor cannot be instantiated to expected type;
found : akka.actor.FSM.Failure
required: scala.util.Try[Int]**
What I would like to do is to show the error message code and sqlState code . This is my code
def registration = Action.async {implicit request=>
val setup =
sqlu"""INSERT Logic"""
db.run(setup.asTry).map { result =>
if(result.isFailure)
{
result match {
case Failure(e: PSQLException) => {
//code: if Error I would like to return message below
Ok(s"PostgresIntegrityConstraintViolationException, code: ${e.getErrorCode}, sql status: ${e.getSQLState}, message: ${e.getMessage}")
}
}
}
Ok(result.toString())
}
}
Whenever there is an error in the Database it falls inside the result.isFailure now I would just like to get the PSQLException ErrorCode and SQLState . I do not really care about matching or anything. I am doing this for a web service API so if for example I see that error code 23008 corresponds with duplicate email then I can give user's a generic message such as "Duplicate Email" . Any suggestions would be great as I'm new to Scala and Slick . I am using slick version 3.11
The error message is coming from this part
result match {
case Failure(e: PSQLException) => {
//code: if Error I would like to return message below
Ok(s"PostgresIntegrityConstraintViolationException, code: ${e.getErrorCode}, sql status: ${e.getSQLState}, message: ${e.getMessage}")
}
}
Considering i understood your question correctly, you can use nested Case. Inside the case check the error code, if the error code is as expected show the Msg.
case Failure(e: PSQLException) => e.code match{
case "23008" => println("Duplicate email")
case - => println("Some generic msg")
}
Please let me know if I understood it wrong.