【问题标题】:How should I use MayErr[IntegrityConstraintViolation,Int] in Scala and Anorm?我应该如何在 Scala 和 Anorm 中使用 MayErr[IntegrityConstraintViolation,Int]?
【发布时间】:2011-06-12 18:57:57
【问题描述】:

我使用Anorm 进行数据库查询。当我执行executeUpdate() 时,我应该如何进行正确的错误处理?返回类型为MayErr[IntegrityConstraintViolation,Int],这是Set还是Map?

有一个example,但是我不明白我应该如何处理返回值:

val result = SQL("delete from City where id = 99").executeUpdate().fold( 
    e => "Oops, there was an error" , 
    c => c + " rows were updated!"
)

如何检查查询是否失败? (使用result),如果查询成功,如何获取受影响的行数?

目前我使用此代码:

SQL(
"""
INSERT INTO users (firstname, lastname) VALUES ({firstname}, {lastname})
"""
).on("firstname" -> user.firstName, "lastname" -> user.lastName)
    .executeUpdate().fold(
            e => "Oops, therw was an error",
            c => c + " rows were updated!"
)

但我不知道我的错误处理代码应该是什么样子。有没有关于如何使用MayErr[IntegrityConstraintViolation,Int]类型的返回值的例子?

【问题讨论】:

    标签: scala error-handling playframework anorm


    【解决方案1】:

    看起来MayErr 正在包装Either。所以它既不是Map 也不是Set,而是一个可以包含两个不同类型对象之一的对象。

    看看this question,您会看到一些处理Either 对象的方法,在这种情况下,它包含一个IntegrityConstraintViolation 或一个Int。参考http://scala.playframework.org/.../Scala$MayErr.html,看起来您可以通过参考值成员e 来获取Either 对象。似乎也可以进行隐式转换,因此您可以将MayErr[IntegrityConstraintViolation,Int] 视为Either[IntegrityConstraintViolation,Int] 而无需进一步的仪式。

    【讨论】:

      【解决方案2】:

      你显然可以做一个

      val updateResult = ....executeUpdate()
      val success = updateResult.fold(e => false, c => true)
      

      看来你也可以调用

      val success = updateResult.isRight
      

      更一般地说,您可以访问包装的 Either

      updateResult.e match {
          case Left(error) => ... do something with error ...
          case Right(updateCount) => ...do something with updateCount...
      }
      

      也许更熟悉 Play 的人会解释为什么 scala.Either 被包裹在 MayErr 中?

      【讨论】:

      • 如示例所示,这样做更容易:updateResult.fold(error => {/* do something with error */}, updateCount => {do something with updateCount})
      猜你喜欢
      • 2021-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-31
      • 1970-01-01
      • 2013-10-20
      • 1970-01-01
      相关资源
      最近更新 更多