Dumka
Dumka

Reputation: 63

Ktor how to handle an empty response

I use Ktor and a line like this myentity = client.get(url) to get and deserialize my entity from API response. It works fine while API returns something, but once API has nothing to return and sends HTTP 204 response, it fails with io.ktor.client.call.NoTransformationFoundException.

I want to find a way how to make client.get() return null instead of throwing that exception. I searched for a solution quite much, but failed to find it. It seems that HttpResponseValidator in initialization of HttpClient might help somehow, but I only find a way how to throw another exception from it, but did not understand how to change a return value.

Upvotes: 4

Views: 3378

Answers (1)

Aleksei Tirman
Aleksei Tirman

Reputation: 7079

You can catch the NoTransformationFoundException and assign null to myentity if an exception is thrown. Here is an example:

import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.engine.okhttp.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.client.request.*
import io.ktor.serialization.kotlinx.json.*
import kotlinx.serialization.json.Json

suspend fun main() {
    val client = HttpClient(OkHttp) {
        install(ContentNegotiation) {
            json(Json { ignoreUnknownKeys = true })
        }
    }

    val response = try {
        client.get("https://httpbin.org/status/204").body<HttpBin>()
    } catch (cause: NoTransformationFoundException) {
        null
    }

    println(response?.origin)
}

@kotlinx.serialization.Serializable
class HttpBin(val origin: String)

Upvotes: 1

Related Questions