为什么 Failure 案例从未达到?

Why the Failure case never reached?

我有一个 websocket 客户端,如下所示:

object Main extends App {

  private val sapServer = "127.0.0.1:8080"

  implicit val system = ActorSystem("WsSystem")
  implicit val materializer = ActorMaterializer()
  implicit val dispatcher = system.dispatcher

  RestartSource.withBackoff(
    minBackoff = 3.seconds,
    maxBackoff = 30.seconds,
    randomFactor = 0.2
  ) { () =>

    // Consider if the server supports websocket or not
    val (supported, source) = Source.tick(1.seconds, 15.seconds, TextMessage.Strict(Monoid.empty[String]))
      .viaMat(Http().webSocketClientFlow(WebSocketRequest(s"ws://$sapServer")))(Keep.right)
      .preMaterialize()

    supported.flatMap { upgrade =>
      //Switching from HTTP to WS protocol
      if (upgrade.response.status == StatusCodes.SwitchingProtocols)
        Future.successful(Done)
      else
        throw new RuntimeException(s"Connection failed: ${upgrade.response.status}")

    }
    source
  }.runWith(Sink.foreach(println))
    .onComplete {
      case Success(_) =>
        //Do nothing
        Unit
      case Failure(_) =>
        println("Probably server is down.")
    }


} 

我还没有启动 websocket 服务器,但是,我希望它在控制台上显示 Probably server is down.。但是我得到了:

[WARN] [06/09/2019 15:06:25.823] [WsSystem-akka.actor.default-dispatcher-14] [RestartWithBackoffSource(akka://WsSystem)] Restarting graph due to failure. stack_trace:  (akka.stream.StreamTcpException: Tcp command [Connect(127.0.0.1:8080,None,List(),Some(10 seconds),true)] failed because of java.net.ConnectException: Connection refused)
[WARN] [06/09/2019 15:06:32.674] [WsSystem-akka.actor.default-dispatcher-13] [RestartWithBackoffSource(akka://WsSystem)] Restarting graph due to failure. stack_trace:  (akka.stream.StreamTcpException: Tcp command [Connect(127.0.0.1:8080,None,List(),Some(10 seconds),true)] failed because of java.net.ConnectException: Connection refused)
[WARN] [06/09/2019 15:06:45.367] [WsSystem-akka.actor.default-dispatcher-3] [RestartWithBackoffSource(akka://WsSystem)] Restarting graph due to failure. stack_trace:  (akka.stream.StreamTcpException: Tcp command [Connect(127.0.0.1:8080,None,List(),Some(10 seconds),true)] failed because of java.net.ConnectException: Connection refused)
[WARN] [06/09/2019 15:07:09.828] [WsSystem-akka.actor.default-dispatcher-13] [RestartWithBackoffSource(akka://WsSystem)] Restarting graph due to failure. stack_trace:  (akka.stream.StreamTcpException: Tcp command [Connect(127.0.0.1:8080,None,List(),Some(10 seconds),true)] failed because of java.net.ConnectException: Connection refused) 

问题是,如何捕获StreamTcpException异常?

supported 未来是因连接异常而失败的未来,而不是 RestartSource.withBackoff 正在创建的未来。做类似的事情:

supported.flatMap {...}.onComplete {
  case Failure(_) =>
    println("Probably server is down.")
}

将打印您期望的消息。