Why is Akka Streams swallowing my exceptions?

前端 未结 3 1018
悲&欢浪女
悲&欢浪女 2021-02-04 03:38

Why is the exception in

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

object TestExceptionHandling {
  d         


        
3条回答
  •  旧巷少年郎
    2021-02-04 03:57

    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)
    

    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()
    

    since run() returns Unit.

提交回复
热议问题