2017-02-07 51 views
6

我有下面的场景,我尝试使用漂亮的DBIO操作来实现它。在光滑的dbio操作中处理清理操作错误

Execute a batch Insert operation. On success, return the inserted result On failure, 
      -> if the failure is due to duplicate value in a particular column, then remove the duplicates from the list, and try batch insert again. If the second batch insert is successful, return a successful future with the second inserted list, else the failed future of the 2nd batch insert. 
      -> if the failure is due to something else, then throw that exception 

对于上述情况,我尝试使用cleanUp操作。但是,如果主要操作失败,我不知道如何返回cleanUp操作结果。

如何使用DBIO操作来实现我的要求操作错误处理?

def insertBatchAndReturnQuery(rowList: List[E]): FixedSqlAction[Seq[E], NoStream, Write] = { 
    query returning query ++= rowList 
} 


def insert(entities: List[E]): Future[Seq[E]] = { 
    val q = insertBatchAndReturnQuery(entities).cleanUp { 
     case Some(ex) => ex match { 
     case b: PSQLException => { 
      if (b.getSQLState.equals("23505")) { 
      //unique key exception, handle this by removing the duplicate entries from the list 
      ??? 
      } else { 
      throw new Exception("some database exception") 
      } 
     } 
     } 
     case None => insertBatchAndReturnQuery(Nil) 
    } 
    db.run(q) 
    } 

这里,查询是TableQuery [T]。

油滑版本:3.2.0-M2

回答

0

您可以从cleanUp它返回与同类型的第一个行动的价值诉讼的签名看,所以也没有办法,你会能够从cleanUp操作返回值。

如果您希望返回第二个值,则需要使用asTry将错误包装到Try中,然后使用flatMap。对于手头的问题,它会是这个样子:

val q = insertBatchAndReturnQuery(entities).asTry.flatMap { 
    case Failure(b: PSQLException) if b.getSQLState == "23505" => 
    //unique key exception, handle this 
    //by removing the duplicate entries from the list 
    ??? 
    case Failure(e) => 
    throw new Exception("some database exception") 
    case Success(count) => DBIO.successful(count) 
} 

但是文件警告说,使用asTry失去流能力,所以你可能希望找到另一种方式来做到这一点...