如何在Akka流中引发异常?

时间:2019-04-22 18:54:18

标签: scala akka akka-stream

我想抛出如下异常:

  Source.empty
      .map {
        throw new RuntimeException("Failed")
      }
      .runWith(Sink.foreach(println))
      .onComplete {
        case Success(_) =>
          println()
        case Failure(e) =>
          println(s"Thrown ${e.getMessage}")
      }  

但是该异常不会出现在onComplete方法中。打印

Exception in thread "main" java.lang.RuntimeException: Failed
    at com.sweetsoft.App$.main(App.scala:30)
    at com.sweetsoft.App.main(App.scala) 

如何引发异常,该异常将停止流并在末尾出现?

1 个答案:

答案 0 :(得分:2)

Akka内置了错误处理功能:Akka Supervision Strategies

val testSupervisionDecider: Supervision.Decider = {
        case ex: java.lang.RuntimeException =>
          println(s"some run time exception ${ex.getMessage}")
          Supervision.Stop
        case ex: Exception =>
          println("Exception occurred and stopping stream",
            ex)
          Supervision.Stop
      }

您可以将监督决策者用作

val list = List.range(1, 100)

  Source(list).map { item =>
    if ((item % 2) == 0) {
      throw new RuntimeException(s"$item")
    } else {
      item
    }
  }.withAttributes(ActorAttributes.supervisionStrategy(testSupervisionDecider))
    .runWith(Sink.foreach(println)).onComplete {
    case Success(_) =>
      println()
    case Failure(e) =>
      println(s"Thrown ${e.getMessage}")
  }