2

In Slick 3.x, I use the code below to wrap the fact that the database is MySQL. This allows me to declare MySQLDriver just one time in the entire application:

package util

import slick.driver.MySQLDriver

trait DbDriver extends MySQLDriver {
  val dbApi = api
}

object DbDriver extends DbDriver

Then in the classes that use Slick I import as follows (instead of a database-specific driver):

import util.DbDriver.api._

Now, I need to catch duplicate insert exceptions. To do that, I use a MySql class:

case Success(res) => 
  // insert succeeded, no duplicate exception
case Failure(e: MySQLIntegrityConstraintViolationException) =>
  // duplicate exception
case Failure(e) => 
  // other failures

But this forces me to import in every class com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException. Is there a way to include it in the generic trait declaration DbDriver?

This is my attempt (that does NOT work):

Declaring:

class Duplicate extends        
  com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException

And catching with:

case Failure(e: Duplicate) => // print something
Jeffrey Chung
  • 19,319
  • 8
  • 34
  • 54
ps0604
  • 1,227
  • 23
  • 133
  • 330

1 Answers1

1

You could define a type alias:

trait DbDriver extends MySQLDriver {
  val dbApi = api
}

object DbDriver extends DbDriver {
  type Duplicate = com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException
}

Import this type and you can pattern match on it:

case Success(res) => 
  // insert succeeded, no duplicate exception
case Failure(e: Duplicate) =>
  // duplicate exception
case Failure(e) => 
  // other failures
Jeffrey Chung
  • 19,319
  • 8
  • 34
  • 54