From 2dff398baa80a8823d574931d8c05c4a609e445b Mon Sep 17 00:00:00 2001 From: dankito Date: Sat, 13 Jun 2020 23:53:13 +0200 Subject: [PATCH] Implemented catching exceptions --- .../banking/fints/webclient/KtorWebClient.kt | 24 ++++++++++++++----- 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/fints4k/src/commonMain/kotlin/net/dankito/banking/fints/webclient/KtorWebClient.kt b/fints4k/src/commonMain/kotlin/net/dankito/banking/fints/webclient/KtorWebClient.kt index 0c123cae..26450281 100644 --- a/fints4k/src/commonMain/kotlin/net/dankito/banking/fints/webclient/KtorWebClient.kt +++ b/fints4k/src/commonMain/kotlin/net/dankito/banking/fints/webclient/KtorWebClient.kt @@ -9,10 +9,16 @@ import io.ktor.http.ContentType import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.async import kotlinx.coroutines.cancel +import net.dankito.banking.fints.util.log.LoggerFactory open class KtorWebClient : IWebClient { + companion object { + private val log = LoggerFactory.getLogger(KtorWebClient::class) + } + + protected val client = HttpClient() { } @@ -31,13 +37,19 @@ open class KtorWebClient : IWebClient { override fun post(url: String, body: String, contentType: String, userAgent: String): WebClientResponse { try { val job = GlobalScope.async { - val clientResponse = client.post(url) { - this.body = TextContent(body, contentType = ContentType.Application.OctetStream) + try { + val clientResponse = client.post(url) { + this.body = TextContent(body, contentType = ContentType.Application.OctetStream) + } + + val responseBody = clientResponse.readText() + + WebClientResponse(clientResponse.status.value == 200, clientResponse.status.value, body = responseBody) + } catch (e: Exception) { + log.error(e) { "Could not send request to url '$url'" } + + WebClientResponse(false, error = e) } - - val responseBody = clientResponse.readText() - - WebClientResponse(clientResponse.status.value == 200, clientResponse.status.value, body = responseBody) } while (job.isCompleted == false) { } // let's warm the CPU to get suspend function synchronous (runBlocking is not available in common projects)