How to catch slick postgres exceptions for duplicate key value violations

后端 未结 2 1217
挽巷
挽巷 2020-12-09 11:23

My table has a unique index on a pair of columns in my postgresql database.

I want to know how I can catch a duplicate key exception when I am inserting:

<         


        
2条回答
  •  眼角桃花
    2020-12-09 12:09

    In Slick 3.x you can use asTry.

    I'm using MySQL, but the same code can be used for PostgreSQL, only the exceptions are different.

    import scala.util.Try
    import scala.util.Success
    import scala.util.Failure
    
    db.run(myAction.asTry).map {result =>  
    
      result match {
    
        case Success(res) => 
          println("success")
          // ...
    
        case Failure(e: MySQLIntegrityConstraintViolationException) => {
          //code: 1062, status: 23000, e: Duplicate entry 'foo' for key 'name'
          println(s"MySQLIntegrityConstraintViolationException, code: ${e.getErrorCode}, sql status: ${e.getSQLState}, message: ${e.getMessage}")
          // ...
        }
    
        case Failure(e) => {
          println(s"Exception in insertOrUpdateListItem, ${e.getMessage}")
          // ...
        }
      }
    }
    

    Note: It's also possible to map the action (myAction.asTry.map ...) instead of the future returned by db.run.

提交回复
热议问题