How to manage DB related Exceptions in Play! 2.0/Scala using Anorm

Viewed 2599

I am currently Play!ing with Play 2.0 (Scala). I must admit that it's a lot of fun. I have a question though related to database operations exceptions.

Let's say I have Car as a domain class and that I have an integrity constraint on one of the field, let's say the model so that in the db I can not have two (2) rows having the same model name :

case class Car(id: Pk[Long], name: String, model: String)

I am trying to insert a record in the DB like this :

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 don't catch the exception like in the previous code, then when I call this method from my controller with model having a value already existing in the database, I have the following exception thrown :

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry 'Enzo' for key 'model'

Is there a way to catch the MySQLIntegrityConstraintViolationException instead of Exception so that I have a fine-grained control over what can go wrong and then provide a more concise feed-back to my user for example (in a browser or on a mobile device) ?

Is this the best way to handle DB-related operations and exceptions or is there any best-practices that everybody use ?

thanks in advance,

2 Answers
Related