繁体   English   中英

使用 Try 在 Scala 中处理错误的最佳实践

[英]Best practices on error handling in Scala using Try

我处理异常如下:

def calculate(input: Option[Double]): Try[String] =
  Try {
    input match {
      case (Some(value)) => value.toString
      case (None) => throw new IllegalArgumentException("No value found")
    }
}

在客户端代码中:

val result = calculate(....)

result match {
    case Success(i) => println(i)
    case Failure(s) => throw s // or log(s) to log the issue and continue
}

对于干净优雅的代码库,它是足够好的实践还是可以做得更好?

Try通常用于覆盖可能引发错误的部分,例如在使用某些 Java 库时可能引发异常的情况。 但是,如果您想返回可能的错误并强制客户端处理它, Either[A, B]是更好的选择,至少因为您可以为Left[A]指定更精确的错误类型并安全地与您的错误类型进行模式匹配A类型,而不是对某些Throwable进行可能不正确的模式匹配,就像您对Failure(t)所做的那样。

因此,在您的情况下,可能的解决方案如下所示:

sealed trait CalculationError
case class Error1(cause: String) extends CalculationError

def calculate(input: Option[Double]): Either[CalculationError, String] =
    input match {
      case (Some(value)) => Right(value.toString)
      case (None) => Left(Error1("No value found"))
    }
}

val result = calculate(....)

result match {
    case Right(i) => println(i)
    case Left(Error1(s)) => println(s)
}

这是更安全的方法,因为您稍后可以添加另一种类型的错误,例如case class Error2(cause: String) extends CalculationError并且在客户端模式匹配代码部分,compile 将显示一条警告消息,您错过了新错误的处理: Match is not exhaustive Failure(t) compile 的情况下,将无法提示此类警告,因此在错误处理方面更容易出错。

希望这可以帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM