scala's尝试优雅的错误行为

Pab*_*dez 3 refactoring scala try-catch

在scala中有更优雅的方法吗?

def doTheDangerousThing(): Try[Result] = {
  val result = Try(dangerousOp)

  if (result.isFailure) {
     println("error")
  }

  result
}
Run Code Online (Sandbox Code Playgroud)

vpt*_*ron 13

我认为你的if语句完全有效.这是另一种选择:

def doTheDangerousThing(): Try[Result] = Try(dangerousOp) recoverWith {
    case exception => println("error"); Failure(exception)
}
Run Code Online (Sandbox Code Playgroud)

  • 虽然有效(我的,就是这样),但它看起来有点势在必行。如果有一个 `recoverWith` 的变体只是为了产生副作用,而不必再次返回 `Failure`,那就太好了。 (2认同)

Jam*_*dam 2

好吧,我想你可以这样做:

def doTheDangerousThing(): Option[Result] = 
  Try(dangerousOp) match {
    case Success(result) => Some(result)
    case Failure(e) => None //might want to log the error as well
  }
Run Code Online (Sandbox Code Playgroud)

  • 该代码如何替换问题中的代码片段?更改返回类型有什么意义?我认为 Pablo 只是对替换 if 语句感兴趣。 (2认同)