Come dovrei usare MayErr [IntegrityConstraintViolation, Int] in Scala e Anorm?
-
27-10-2019 - |
Domanda
Anorm da fare query di database. Quando faccio un executeUpdate()
, come devo fare una corretta gestione degli errori? ha tipo di ritorno MayErr[IntegrityConstraintViolation,Int]
, è presente un set o una mappa?
C'è un esempio , ma io non lo fanno capisco come devo gestire il valore di ritorno:
val result = SQL("delete from City where id = 99").executeUpdate().fold(
e => "Oops, there was an error" ,
c => c + " rows were updated!"
)
Come faccio a verificare se la query non è riuscita? (Utilizzando result
), e come faccio a ottenere il numer di righe interessate, se la query ha avuto successo?
Al momento io uso questo codice:
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!"
)
Ma io non so come il mio codice di gestione degli errori dovrebbe essere simile. C'è un esempio su come utilizzare il valore di ritorno di tipo MayErr[IntegrityConstraintViolation,Int]
?
Soluzione
Si potrebbe ovviamente fare un
val updateResult = ....executeUpdate()
val success = updateResult.fold(e => false, c => true)
Sembra che si può anche chiamare
val success = updateResult.isRight
Più in generale, è possibile accedere al entrambi avvolto con
updateResult.e match {
case Left(error) => ... do something with error ...
case Right(updateCount) => ...do something with updateCount...
}
Forse qualcuno più familiarità con Play spiegherebbe perché scala.Either è avvolto in MayErr?
Altri suggerimenti
Sembra che MayErr
è avvolgente Either
. Quindi è né un Map
né una Set
, ma piuttosto un oggetto che può contenere uno dei due oggetti in modo diverso tipizzati.
Date un'occhiata a questa domanda , e vedrete alcune modi di elaborazione un oggetto o, che in questo caso contiene sia un IntegrityConstraintViolation o un Int. Facendo riferimento a http: // Scala. playframework.org/.../Scala$MayErr.html , sembra che si può afferrare un oggetto Sia con riferimento al valore di e
membro. Sembra che ci sia una conversione implicita disponibile anche, in modo da poter trattare un solo MayErr[IntegrityConstraintViolation,Int]
come Either[IntegrityConstraintViolation,Int]
senza ulteriori cerimonia.