我想抛出如下异常:
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)
如何引发异常,该异常将停止流并在末尾出现?
答案 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}")
}