如何在处理某些异常时很好地将 Try[Unit] 转换为 Unit?

How to nicely transform a Try[Unit] to a Unit while handling certain exceptions?

我有这样的东西:

def mySideEffectingMethod(): Unit = {
  Try(someSideEffectingJavaMethod()) match {
    case Failure(_: SomeExpectedException) => someSideEffectingJavaMethod() //perhaps attempt it again, for example
    case Failure(ex) => throw ex
    case Success(_) => //unit
  }
}

有什么方法可以让我变丑case Success(_) => //unit?我不认为 recoverrecoverWith 会削减它,因为在这种情况下它们会 return Try[Unit] 而不是 Unit 从而抑制非预期的异常。

当您想以功能方式处理异常和错误时,您可以使用Try[T] monad。特别是,使用 Try[T] monad 可以累积异常并继续详细说明属于 Success[T] 的结果,Success[T]Try[T].

的子类

在你的情况下,你似乎只需要处理异常行为。在这种情况下,您可以简单地使用 try 语句。

def mySideEffectingMethod = {
   try {
     someSideEffectingJavaMethod 
   } catch {
     case _: SomeExpectedException => someSideEffectingJavaMethod()    
     //perhaps attempt it again, for example
     case ex => throw ex
   }
}

在您的情况下,您可以使用 try 语句,因为您正在对输入做一些 副作用。但是,如果你采用更 功能性 的方法,这意味着完全没有副作用,你必须改造 Try monad。

我认为解释如何在 Scala 中以函数式方式处理异常的最佳指南之一是 The Neophyte's Guide to Scala Part 6: Error Handling With Try

使用 Try 类型的替代方法:

def mySideEffectingMethod(): Unit = {
  Try(someSideEffectingJavaMethod()).failed.foreach {
    case _: SomeExpectedException => 
      //perhaps attempt it again, for example
      someSideEffectingJavaMethod() 
    case ex => throw ex
  }
}