我想利用scalazs析取将异常包装在自己的错误类型中。
以下代码应编译
trait Result
trait Error extends Result
object MyError extends Error
object OK extends Result
val r: Error \/ OK.type = tryCatchIn(_ => MyError /*:Error*/) {
val result: Error \/ OK.type = ???
result
}
我想保留柯里化语法并且不喜欢显式键入MyError
.
我目前的解决方案是双重使用
def tryCatchIn2[L, R](exceptionTransformer: Throwable => L, `finally`: => Unit = () => ()): CatchFinally[L] = {
new CatchFinally(exceptionTransformer, `finally`)
}
class CatchFinally[L](val exceptionTransformer: Throwable => L, `finally`: => Unit = () => ()) {
def apply[L2 >: L, R](block: => L2 \/ R): L2 \/ R = try {
block
} catch {
case NonFatal(e) => -\/(exceptionTransformer(e))
} finally {
`finally`
}
}
我最初的咖喱方法会更好地反映我的意图,但我无法让它发挥作用:
def tryCatchIn[L, R, L2 >: L](exceptionContainer: Throwable => L, `finally`: => Unit = () => ())
(block: => L2 \/ R): L2 \/ R = {
try {
block
} catch {
case NonFatal(e) => -\/(exceptionContainer(e))
} finally {
`finally`
}
}
是否有更清晰的解决方案?