scala - 捕获 map 内的异常

标签 scala loops dictionary exception scala-collections

在 Scala 中迭代循环时处理异常的最佳方法是什么?

例如,如果我有 convert()可能引发异常的方法,我想捕获该异常,记录它并继续迭代。有没有一种“scala”方法可以做到这一点?

理想情况下,我想要这样的东西......

val points: Seq[Point] = ...
val convertedPoints: Seq[ConvertedPoint] = points.map(
   p => {
     try { p.convert() } 
     catch { case ex: Exception => logger.error("Could not convert", ex) }
})

您无法执行上述代码,因为它不是从一个列表到另一个列表的直接映射(您返回 Seq[Any] 而不是 Seq[ConvertedPoint] )。

最佳答案

flatMap 可能是您正在寻找的,但是 map 函数具有日志记录副作用,并且如果点是 View ,这些副作用可能不会立即发生:

val convertedPoints = points.view.flatMap { p =>
  try { 
    Some(p.convert) 
  } catch {
    case e : Exception =>
    // Log error
    None
  }
}
println("Conversion complete")
println(convertedPoints.size + " were converted correctly")

这将打印:

Conversion complete
[Error messages]
x were converted correctly

就你的情况而言,放弃 View 就可能没问题。 :)

要使转换成为纯函数(无副作用),您可能会使用 Either。尽管我认为不值得在这里付出努力(除非您实际上想对错误做一些事情),但这里有一个非常完整的使用它的示例:

case class Point(x: Double, y: Double) {
  def convert = {
    if (x == 1.0) throw new ConversionException(this, "x is 1.0. BAD!")
    else ConvertedPoint(x, y)
  }
}
case class ConvertedPoint(x: Double, y: Double)
class ConversionException(p: Point, msg: String) extends Exception(msg: String)


val points = List(Point(0,0), Point(1, 0), Point(2,0))

val results = points.map { p =>
  try {
    Left(p.convert)
  } catch {
    case e : ConversionException => Right(e)
  }
}

val (convertedPoints, errors) = results.partition { _.isLeft }

println("Converted points: " + convertedPoints.map(_.left.get).mkString(","))
println("Failed points: " + errors.map( _.right.get).mkString(","))

关于scala - 捕获 map 内的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4089537/

相关文章:

java - 使用 Either 处理失败 -> 堆栈跟踪在哪里?

java - 如何在循环内另外迭代 for(String s : st) in java?

javascript - 如何使用for循环创建javascript对象

java - Java 中是否有任何 map 实现可以给我一个 map ,其中条目的排序方式与我放入它们的方式相同?

python - 使用 for 循环创建数据副本

java - 确定获得(纬度、经度)对的正确顺序以绘制 N 边的闭合正多边形的方法

scala - 按名称重复的参数

inheritance - Scala中是否有一个“SELF”类型代表当前类型?

scala - Spark配置: SPARK_MEM vs. SPARK_WORKER_MEMORY

python - 应用 Pandas 创建列方法和函数