diff --git a/CHANGELOG.md b/CHANGELOG.md index f40916f633..b131151a37 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,7 @@ ### 0.20.2 * New exception type `MessageIsNotModifierException` was added +* Now exceptions in requests will be caught correctly ## 0.19.0 ImplicitReflection removing diff --git a/src/commonMain/kotlin/com/github/insanusmokrassar/TelegramBotAPI/bot/Ktor/KtorRequestsExecutor.kt b/src/commonMain/kotlin/com/github/insanusmokrassar/TelegramBotAPI/bot/Ktor/KtorRequestsExecutor.kt index dd2ccb174f..c75eb8bf95 100644 --- a/src/commonMain/kotlin/com/github/insanusmokrassar/TelegramBotAPI/bot/Ktor/KtorRequestsExecutor.kt +++ b/src/commonMain/kotlin/com/github/insanusmokrassar/TelegramBotAPI/bot/Ktor/KtorRequestsExecutor.kt @@ -13,6 +13,8 @@ import com.github.insanusmokrassar.TelegramBotAPI.utils.TelegramAPIUrlsKeeper import io.ktor.client.HttpClient import io.ktor.client.call.HttpClientCall import io.ktor.client.call.receive +import io.ktor.client.features.ClientRequestException +import io.ktor.client.response.readText import kotlinx.coroutines.delay import kotlinx.serialization.json.Json @@ -48,26 +50,36 @@ class KtorRequestsExecutor( if (call == null) { throw IllegalArgumentException("Can't execute request: $request") } - val content = call.response.receive() - val responseObject = jsonFormatter.parse(Response.serializer(), content) + try { + val content = call.response.receive() + val responseObject = jsonFormatter.parse(Response.serializer(), content) - (responseObject.result ?.let { - jsonFormatter.fromJson(request.resultDeserializer, it) - } ?: responseObject.parameters ?.let { - val error = it.error - if (error is RetryAfterError) { - delay(error.leftToRetry) - execute(request) - } else { - null - } - } ?: call.let { + (responseObject.result?.let { + jsonFormatter.fromJson(request.resultDeserializer, it) + } ?: responseObject.parameters?.let { + val error = it.error + if (error is RetryAfterError) { + delay(error.leftToRetry) + execute(request) + } else { + null + } + } ?: call.let { + throw newRequestException( + responseObject, + content, + "Can't get result object from $content" + ) + }) + } catch (e: ClientRequestException) { + val content = e.response.readText() + val responseObject = jsonFormatter.parse(Response.serializer(), content) throw newRequestException( responseObject, content, "Can't get result object from $content" ) - }) + } } }