How should I use MayErr[IntegrityConstraintViolation,Int] in Scala and Anorm?

放肆的年华 提交于 2019-12-23 15:43:57

问题


I use Anorm to do database queries. When I do an executeUpdate(), how should I do proper error handling? it has return type MayErr[IntegrityConstraintViolation,Int], is this a Set or a Map?

There is an example, but I don't understand how I should handle the return value:

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

How do I check if the query failed? (using result), and how do I get the numer of affected rows if the query was successful?

At the moment I use this code:

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!"
)

But I don't know how my error-handling code should look like. Is there any example on how to use the return value of type MayErr[IntegrityConstraintViolation,Int]?


回答1:


You could obviously do a

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

It looks like you can also call

val success = updateResult.isRight

More generally, you can access the wrapped Either with

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

Maybe someone more familiar with Play would explain why scala.Either is wrapped in MayErr?




回答2:


It looks like MayErr is wrapping Either. So it's neither a Map nor a Set, but rather an object that can contain one of two differently typed objects.

Take a look at this question, and you'll see some ways of processing an Either object, which in this case contains either an IntegrityConstraintViolation or an Int. Referring to http://scala.playframework.org/.../Scala$MayErr.html, it looks like you can grab an Either object by referring to the value member e. There seems to be an implicit conversion available too, so you can just treat a MayErr[IntegrityConstraintViolation,Int] as an Either[IntegrityConstraintViolation,Int] without further ceremony.



来源:https://stackoverflow.com/questions/6323961/how-should-i-use-mayerrintegrityconstraintviolation-int-in-scala-and-anorm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!