From b62e39b4d14b25bdbfeaab2f5e7393c9ef28e86a Mon Sep 17 00:00:00 2001
From: Him188 <Him188@mamoe.net>
Date: Tue, 27 Apr 2021 21:48:05 +0800
Subject: [PATCH] Set state to CLOSED on failure during connecting

---
 .../network/impl/netty/NettyNetworkHandler.kt  | 18 ++++++++++++++----
 1 file changed, 14 insertions(+), 4 deletions(-)

diff --git a/mirai-core/src/commonMain/kotlin/network/impl/netty/NettyNetworkHandler.kt b/mirai-core/src/commonMain/kotlin/network/impl/netty/NettyNetworkHandler.kt
index 6266692b7..649535c4e 100644
--- a/mirai-core/src/commonMain/kotlin/network/impl/netty/NettyNetworkHandler.kt
+++ b/mirai-core/src/commonMain/kotlin/network/impl/netty/NettyNetworkHandler.kt
@@ -229,10 +229,11 @@ internal open class NettyNetworkHandler(
                         return@invokeOnCompletion // already been switching to CONNECTING
                     }
                     setState(null) { // ignore replication check
-                        StateConnecting(
-                            collectiveExceptions.apply { collect(error) },
-                            wait = true
-                        )
+//                        StateConnecting(
+//                            collectiveExceptions.apply { collect(error) },
+//                            wait = true
+//                        )
+                        StateClosed(collectiveExceptions.collectGet(error))
                     } // logon failure closes the network handler.
                 }
                 // and this error will also be thrown by `StateConnecting.resumeConnection`
@@ -265,6 +266,15 @@ internal open class NettyNetworkHandler(
     protected inner class StateLoading(
         private val connection: NettyChannel
     ) : NettyState(State.LOADING) {
+        init {
+            coroutineContext.job.invokeOnCompletion {
+                if (it != null && it !is CancellationException && it !is StateSwitchingException) {
+                    connection.close()
+                    setState { StateClosed(it) }
+                }
+            }
+        }
+
         override suspend fun sendPacketImpl(packet: OutgoingPacket): Boolean {
             connection.writeAndFlush(packet)
             return true