Can anyone tell me some knowledge and usage of ‘scala.util.control.Exception._’?
Such as
val rollbackIfException = handling(classOf[Throwable]) by { //???
t =>
{
tx.rollback()
throw t
}
}
rollbackIfException[A] { //??
val session = new Session(conn, Some(tx))
val result: A = execution(session)
tx.commit()
result
}
Is there something specific you want to know that isn’t covered in the Scaladoc?
fwiw, I don’t think scala.util.control.Exception
is widely known or widely used.
Hi @yangmingsen,
You didn’t explain the problem you’re having, but I’m guessing it’s to do with the [A]
type parameter?
You need to define rollbackIfException
as a function with a type parameter for it to work, and I also passed it the tx
:
imporWelcome to Scala 2.13.1 (OpenJDK 64-Bit Server VM, Java 11.0.6).
Type in expressions for evaluation. Or try :help.
scala> import scala.util.control.Exception._
import scala.util.control.Exception._
scala> trait Tx {
| def commit(): Unit
| def rollback(): Unit
| }
defined trait Tx
scala> class FakeTx extends Tx {
| def commit() = println("committing")
| def rollback() = println("rolling back")
| }
defined class FakeTx
scala> def rollbackIfException[A](tx: Tx) =
| handling[A](classOf[Throwable]).by { t => tx.rollback(); throw t }
rollbackIfException: [A](tx: Tx)util.control.Exception.Catch[A]
scala> val tx: Tx = new FakeTx
tx: Tx = FakeTx@531bec12
scala> rollbackIfException[String](tx) {
| val result = "woohoo"
| tx.commit()
| result
| }
committing
res1: String = woohoo
scala> rollbackIfException[String](tx) {
| val result = throw new Exception("boom")
| tx.commit()
| result
| }
rolling back
java.lang.Exception: boom
at .$anonfun$res2$1(<console>:2)
at scala.util.control.Exception$Catch.apply(Exception.scala:227)
... 43 elided