Question

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]?

Was it helpful?

Solution

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?

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top