【问题标题】:catch custom Exception in Apache Spark在 Apache Spark 中捕获自定义异常
【发布时间】:2018-02-15 02:08:50
【问题描述】:

我无法在 Apache Spark 中捕获自定义异常。

当我在这样的 foreach 循环中对数据集进行验证时

ds.foreach(
        entry=> {
          validate(entry)
        })

当条目无效时,验证函数会抛出自定义异常。

但是在 catch 块中,我无法捕捉到我的自定义异常,只有一个 SparkException 被抛出并且可以被捕捉到:

case customException : CustomException =>
    //is never catched
case exception : SparkException =>
    //can be catched

我该如何处理?我需要捕获所有由 validate 方法抛出的不同类型的异常。一种方法是读取包含原始异常的 SparkException 消息,但这可能不是一个好的设计。

有什么想法吗?

【问题讨论】:

    标签: apache-spark exception


    【解决方案1】:

    尝试匹配原因,而不是匹配基本异常:

    import org.apache.spark.rdd.RDD
    
    def ignoreArithmeticException(rdd: RDD[java.lang.Integer]) = try {
      rdd.foreach(1 / _)
    } catch {
      case e: SparkException => e.getCause match  {
        case _: java.lang.ArithmeticException => 
          println("Ignoring ArithmeticException")
        case _ => throw e
      }
    }
    

    这将用于捕获:

    Try(ignoreArithmeticException(sc.parallelize(Seq(0))))
    
    00/00/00 00:00:00 ERROR Executor: Exception in task 3.0 in stage 35.0 (TID 143)
    java.lang.ArithmeticException: / by zero
        at
        ...
    Ignoring ArithmeticException
    res42: scala.util.Try[Unit] = Success(())
    

    (虽然以非常冗长的方式),但不会抓住:

    Try(ignoreArithmeticException(sc.parallelize(Seq(null))))
    
    00/00/00 00:00:00 ERROR Executor: Exception in task 3.0 in stage 38.0 (TID 155)
    java.lang.NullPointerException
        at 
       ...
    res52: scala.util.Try[Unit] =
    Failure(org.apache.spark.SparkException: Job aborted due to stage failure: Task 3 in stage 38.0 failed 1 times, most recent failure: Lost task 3.0 in stage 38.0 (TID 155, localhost, executor driver): java.lang.NullPointerException ....
    

    【讨论】:

      猜你喜欢
      • 2015-06-07
      • 1970-01-01
      • 1970-01-01
      • 2017-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-31
      相关资源
      最近更新 更多