I am currently playing Play with game 2.0 (Scala). I have to admit, this is a lot of fun. I have a question, although it is related to database operations exceptions .
Let's say I have a Car as a domain class and that I have an integrity constraint on one of the fields, say, a model , so in db I can not have two (2) lines having the same model name:
case class Car(id: Pk[Long], name: String, model: String)
I am trying to insert a record in the database as follows:
def create(car: Car): Option[Long] = { DB.withConnection { implicit connection => try { SQL("insert into cars (name, model) values ({name},{model}").on("name" -> car.name, "model" -> car.model).executeInsert() } catch { case e: Exception => { Logger.debug(e.getMessage()) None } } }
if I do not catch the exception, as in the previous code, then when I call this method from my controller with a model that has a value that already exists in the database, I get the following exception:
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry 'Enzo' for key 'model'
Is there a way to catch a MySQLIntegrityConstraintViolationException instead of an Exception so that I have fine-grained control over what might go wrong and then provide a more compressed feed back to my user, for example (in a browser or on a mobile device)?
Is this the best way to handle database operations and exceptions, or are there any better methods that everyone uses?
thanks in advance,