From 2252683ceeb760bd80257d4032572d76e4458c12 Mon Sep 17 00:00:00 2001 From: Him188 Date: Tue, 27 Dec 2022 17:28:52 +0000 Subject: [PATCH] [core] Ensure Bot's CoroutineScope is always cancelled on `Bot.close` if `network.close` threw an exception --- .../src/commonMain/kotlin/AbstractBot.kt | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/mirai-core/src/commonMain/kotlin/AbstractBot.kt b/mirai-core/src/commonMain/kotlin/AbstractBot.kt index 26c220a1b..f5e1655bb 100644 --- a/mirai-core/src/commonMain/kotlin/AbstractBot.kt +++ b/mirai-core/src/commonMain/kotlin/AbstractBot.kt @@ -110,14 +110,16 @@ internal abstract class AbstractBot constructor( override fun close(cause: Throwable?) { if (!this.isActive) return - if (networkInitialized) { - network.close(cause) - } - - if (cause == null) { - supervisorJob.cancel() - } else { - supervisorJob.cancel(CancellationException("Bot closed", cause)) + try { + if (networkInitialized) { + network.close(cause) + } + } finally { // ensure CoroutineScope is always closed + if (cause == null) { + supervisorJob.cancel() + } else { + supervisorJob.cancel(CancellationException("Bot closed", cause)) + } } }