From f584b2fbd1059134c9f9d15b6e88ee15276ad3fc Mon Sep 17 00:00:00 2001 From: Craig Edwards Date: Tue, 3 Dec 2024 10:54:35 +0000 Subject: [PATCH] catch exceptions on reconnect --- src/dpp/discordclient.cpp | 36 ++++++++++++++++++++++-------------- src/dpp/wsclient.cpp | 4 +++- 2 files changed, 25 insertions(+), 15 deletions(-) diff --git a/src/dpp/discordclient.cpp b/src/dpp/discordclient.cpp index e61fa64f8b..3948132ab9 100644 --- a/src/dpp/discordclient.cpp +++ b/src/dpp/discordclient.cpp @@ -125,28 +125,36 @@ discord_client::~discord_client() void discord_client::on_disconnect() { + if (reconnect_timer != 0U) { + log(dpp::ll_debug, "Lost connection to websocket on shard " + std::to_string(shard_id) + ", reconnection already in progress..."); + return; + } set_resume_hostname(); log(dpp::ll_debug, "Lost connection to websocket on shard " + std::to_string(shard_id) + ", reconnecting in 5 seconds..."); ssl_client::close(); end_zlib(); /* Stop the timer first if its already ticking, to prevent concurrent reconnects */ - if (reconnect_timer != 0U) { - owner->stop_timer(reconnect_timer); - reconnect_timer = 0; - } reconnect_timer = owner->start_timer([this](auto handle) { log(dpp::ll_debug, "Reconnecting shard " + std::to_string(shard_id) + " to wss://" + hostname + "..."); - owner->stop_timer(handle); - reconnect_timer = 0; - cleanup(); - if (timer_handle) { - owner->stop_timer(timer_handle); - timer_handle = 0; + try { + cleanup(); + if (timer_handle) { + owner->stop_timer(timer_handle); + timer_handle = 0; + } + start = time(nullptr); + ssl_client::connect(); + start_connecting(); + run(); + owner->stop_timer(handle); + reconnect_timer = 0; + } + catch (const std::exception &e) { + /* If we get here, the timer will tick again */ + ssl_client::close(); + end_zlib(); + log(dpp::ll_debug, "Error reconnecting shard " + std::to_string(shard_id) + ": " + std::string(e.what()) + "; Retry in 5 seconds..."); } - start = time(nullptr); - ssl_client::connect(); - start_connecting(); - run(); }, 5); } diff --git a/src/dpp/wsclient.cpp b/src/dpp/wsclient.cpp index 1c2ef3763d..ffad79ea3f 100644 --- a/src/dpp/wsclient.cpp +++ b/src/dpp/wsclient.cpp @@ -349,7 +349,9 @@ void websocket_client::on_disconnect() void websocket_client::close() { - this->on_disconnect(); + if (sfd != INVALID_SOCKET) { + this->on_disconnect(); + } this->state = HTTP_HEADERS; ssl_client::close(); }