为什么 Akka Streams 吞下我的异常? [英] Why is Akka Streams swallowing my exceptions?
问题描述
为什么会出现异常
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
后流被停止,但没有记录任何内容.请注意,问题通常不在于日志记录配置,因为如果我在 application.conf
中设置 akka.log-config-on-start = on
,我会看到很多输出代码>文件.
silently ignored? I can see that the stream gets stopped after printing Received 1
, but nothing is logged. Note that the problem is not the logging configuration in general, as I see a lot of output if I set akka.log-config-on-start = on
in my application.conf
file.
推荐答案
我现在使用自定义 Supervision.Decider
来确保正确记录异常,可以像这样设置:
I'm now using a custom Supervision.Decider
that makes sure exceptions are properly logged, that can be set up like this:
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 所指出的那样,在上面给出的示例中,异常也可能被抓住"通过
Also, as has been pointed out by Vikor Klang, in the example given above, the exception could also be "caught" via
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")
}
但是请注意,这种方法对您没有帮助
Note however, that this approach won't help you with
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
.
这篇关于为什么 Akka Streams 吞下我的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!