Implemented catching exceptions

This commit is contained in:
dankito 2020-06-13 23:53:13 +02:00
parent fbaa9fa941
commit 2dff398baa
1 changed files with 18 additions and 6 deletions

View File

@ -9,10 +9,16 @@ import io.ktor.http.ContentType
import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async import kotlinx.coroutines.async
import kotlinx.coroutines.cancel import kotlinx.coroutines.cancel
import net.dankito.banking.fints.util.log.LoggerFactory
open class KtorWebClient : IWebClient { open class KtorWebClient : IWebClient {
companion object {
private val log = LoggerFactory.getLogger(KtorWebClient::class)
}
protected val client = HttpClient() { protected val client = HttpClient() {
} }
@ -31,13 +37,19 @@ open class KtorWebClient : IWebClient {
override fun post(url: String, body: String, contentType: String, userAgent: String): WebClientResponse { override fun post(url: String, body: String, contentType: String, userAgent: String): WebClientResponse {
try { try {
val job = GlobalScope.async { val job = GlobalScope.async {
val clientResponse = client.post<HttpResponse>(url) { try {
this.body = TextContent(body, contentType = ContentType.Application.OctetStream) val clientResponse = client.post<HttpResponse>(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) while (job.isCompleted == false) { } // let's warm the CPU to get suspend function synchronous (runBlocking is not available in common projects)