8

假设我有一些引发异常的函数。我将它们包装好返回Either[Throwable, <function return type>]。(假设我需要Either而不是Try)。

def fooWrapper(arg1: FooArg1, arg2: FooArg2) =
  try Right(foo(arg1, arg2)) catch { case NonFatal(e) => Left(e) }

def barWrapper(arg1: BarArg1, arg2: BarArg2, a3: BarArg3) =
  try Right(bar(arg1, arg2, artg3)) catch { case NonFatal(e) => Left(e) }

...

现在我想编写一个通用包装器来摆脱 bolierpllate 代码。你有什么建议?

4

5 回答 5

9

任何时候你想在 arity 方面做一些通用的东西,Shapeless很可能有你需要的东西。在这种情况下,您可以编写以下内容:

import scala.util.control.NonFatal
import shapeless._, ops.function._

def safeify[F, A <: HList, R, O](f: F)(implicit
  ftp: FnToProduct.Aux[F, A => R],
  ffp: FnFromProduct[A => Either[Throwable, R]]
) = ffp((a: A) =>
  try Right(ftp(f)(a)) catch {
    case NonFatal(ex) => Left(ex)
  }
)

现在假设我们有一个不安全的方法,如下所示:

def bad(s: String, i: Int) = s.toInt / i

我们可以包装它:

scala> val better = safeify(bad _)
better: (String, Int) => Either[Throwable,Int] = <function2>

现在我们不必担心异常:

scala> better("1", 0)
res0: Either[Throwable,Int] = Left(ArithmeticException: / by zero)

scala> better("a", 1)
res1: Either[Throwable,Int] = Left(NumberFormatException: For input string: "a")

这适用于任何旧的FunctionN.

于 2014-05-13T15:18:08.753 回答
4

我会写一些像这样的形式:

 def wrap[Value](f: => Value): Either[Value, Exception] = try{
   Right(f).right
 }
 catch{
   case ex: Exception => Left(ex).right
 }

 def foo(arg1: FooArg1, arg2: FooArg2) = wrap{
   //anything I'd have written before in foo
 }

但这不构成。Try好多了。

更新:如果您只想处理正确的投影,那么只需返回正确的投影。现在它组成了。

于 2014-05-13T14:29:34.010 回答
3

如果您不想修改初始函数定义:

您是否需要一个适用于任意数量参数的包装器,或者您是否可以为每个可能的参数数量使用通用包装器?在后一种情况下,您可以:

def eitherify[A, B, C](f: Function2[A, B, C])(a: A, b: B) = {
    try Right(f(a, b)) catch { case NonFatal(e) => Left(e) }
}
def eitherify[A, B, C, D](f: Function3[A, B, C, D])(a: A, b: B, c: C) = {
    try Right(f(a, b, c)) catch { case NonFatal(e) => Left(e) }
}

这允许你做eitherify(foo)eitherify(bar)等等。

于 2014-05-13T14:34:44.117 回答
3

由于您显然还没有足够的选择,另一种方法是使用ScalaUtils尝试方法。ScalaUtils 是一个非常小的、专注的库,您可能不介意将其添加为依赖项。尝试方法(在 org.scalautils 包对象中)将为您提供一个 Or 类型,您可以在该类型上调用 toEither。我首先建议使用 Try 执行此操作,这样您就不需要添加任何依赖项,但它似乎没有 toEither 方法,这让我感到惊讶。所以这就是 Or 的样子:

scala> import org.scalautils._
import org.scalautils._

scala> def foo(i: Int, s: String): String = { require(i >= 0); s * i }
foo: (i: Int, s: String)String

scala> def bar(b: Boolean, i: Int, s: String): Int = { require(i >= 0); if (b) s.length else i }
bar: (b: Boolean, i: Int, s: String)Int

scala> def foo2(i: Int, s: String) = attempt(foo(i, s)).toEither
foo2: (i: Int, s: String)Either[Throwable,String]

scala> def bar2(b: Boolean, i: Int, s: String) = attempt(bar(b, i, s)).toEither
bar2: (b: Boolean, i: Int, s: String)Either[Throwable,Int]

scala> foo2(2, "ho")
res10: Either[Throwable,String] = Right(hoho)

scala> foo2(-2, "ho")
res11: Either[Throwable,String] = Left(java.lang.IllegalArgumentException: requirement failed)

scala> bar2(true, 3, "ho")
res12: Either[Throwable,Int] = Right(2)

scala> bar2(false, 3, "ho")
res13: Either[Throwable,Int] = Right(3)

scala> bar2(false, -3, "ho")
res14: Either[Throwable,Int] = Left(java.lang.IllegalArgumentException: requirement failed)

抱歉,我最初错过了您想要一种方法。我可能会像 noziar 建议的那样超载:

scala> :paste
// Entering paste mode (ctrl-D to finish)

def safely[A, B, C](f: (A, B) => C): (A, B) => Either[Throwable, C] = (a: A, b: B) => attempt(f(a, b)).toEither
def safely[A, B, C, D](f: (A, B, C) => D): (A, B, C) => Either[Throwable, D] = (a: A, b: B, c: C) => attempt(f(a, b, c)).toEither


// Exiting paste mode, now interpreting.

safely: [A, B, C](f: (A, B) => C)(A, B) => Either[Throwable,C] <and> [A, B, C, D](f: (A, B, C) => D)(A, B, C) => Either[Throwable,D]
safely: [A, B, C](f: (A, B) => C)(A, B) => Either[Throwable,C] <and> [A, B, C, D](f: (A, B, C) => D)(A, B, C) => Either[Throwable,D]

scala> val foo3 = safely { foo _ }
foo3: (Int, String) => Either[Throwable,String] = <function2>

scala> val bar3 = safely { bar _ }    
bar3: (Boolean, Int, String) => Either[Throwable,Int] = <function3>

scala> foo3(2, "ho")
res5: Either[Throwable,String] = Right(hoho)

scala> foo3(-2, "ho")
res6: Either[Throwable,String] = Left(java.lang.IllegalArgumentException: requirement failed)

scala> bar3(true, 3, "ho")
res7: Either[Throwable,Int] = Right(2)

scala> bar3(false, 3, "ho")
res8: Either[Throwable,Int] = Right(3)

scala> bar3(false, -3, "ho")
res9: Either[Throwable,Int] = Left(java.lang.IllegalArgumentException: requirement failed)

如果你想避免过载(和无形),那么另一种选择是磁铁图案。我相信这会让你找到一种安全的方法,但我认为重载会更简单。

于 2014-05-13T16:16:48.010 回答
2

正如您所描述的, Scalaz 有一个偏右的Either调用\/,它可能满足您的需求。您可以fromTryCatch\/对象上使用来删除提到的样板。由于\/是右偏的,它可以用于理解,偏右。

示例用法可能是:

for {
  r1 <- \/.fromTryCatch(something1)
  r2 <- \/.fromTryCatch(something2)
} yield something3(r1, r2)

上面的结果类型将是Throwable \/ A

于 2014-05-13T14:52:02.683 回答