gpt4 book ai didi

scala - 为什么 Akka Streams 会吞下我的异常?

转载 作者:行者123 更新时间:2023-12-03 13:31:15 25 4
gpt4 key购买 nike

为什么在

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.Source

object TestExceptionHandling {
def main(args: Array[String]): Unit = {
implicit val actorSystem = ActorSystem()
implicit val materializer = ActorMaterializer()(defaultActorSystem)

Source(List(1, 2, 3)).map { i =>
if (i == 2) {
throw new RuntimeException("Please, don't swallow me!")
} else {
i
}
}.runForeach { i =>
println(s"Received $i")
}
}
}

默默无视?我可以看到流在打印后停止了 Received 1 ,但没有记录任何内容。请注意,问题通常不是日志配置,因为如果我设置 akka.log-config-on-start = on,我会看到很多输出。在我的 application.conf文件。

最佳答案

我现在使用自定义 Supervision.Decider确保正确记录异常,可以这样设置:

val decider: Supervision.Decider = { e =>
logger.error("Unhandled exception in stream", e)
Supervision.Stop
}

implicit val actorSystem = ActorSystem()
val materializerSettings = ActorMaterializerSettings(actorSystem).withSupervisionStrategy(decider)
implicit val materializer = ActorMaterializer(materializerSettings)(actorSystem)

此外,正如 Vikor Klang 所指出的那样,在上面给出的示例中,异常也可以通过“捕获”
Source(List(1, 2, 3)).map { i =>
if (i == 2) {
throw new RuntimeException("Please, don't swallow me!")
} else {
i
}
}.runForeach { i =>
println(s"Received $i")
}.onComplete {
case Success(_) =>
println("Done")
case Failure(e) =>
println(s"Failed with $e")
}

但是请注意,这种方法不会帮助您
Source(List(1, 2, 3)).map { i =>
if (i == 2) {
throw new RuntimeException("Please, don't swallow me!")
} else {
i
}
}.to(Sink.foreach { i =>
println(s"Received $i")
}).run()

自从 run()返回 Unit .

关于scala - 为什么 Akka Streams 会吞下我的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35631754/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com