为什么失败案例从未到来?

时间:2019-06-09 13:15:15

标签: scala akka akka-stream

我有一个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异常?

1 个答案:

答案 0 :(得分:4)

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

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

将打印您期望的消息。