开发者

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

开发者 https://www.devze.com 2023-03-12 03:25 出处:网络
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?

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(
"开发者_StackOverflow社区""
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]?


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.


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号