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,
I think you are looking like something within these lines:
Important note: make sure you import
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException, and notcom.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException. More precisely, make sure your import matches the exception in your stack trace.As for best-practices, i dont know as i'm also playing with this framework :).
As for feedback to the user ... perhaps the Flash Scope is a good way to communicate one-liners to the 'next page' (e.g. if the car was succesfully stored or not). See: http://www.playframework.org/documentation/2.0/ScalaSessionFlash (Scroll down to 'Flash scope'.)