Is it possible to specify multiple types to return...
# ktor
g
Is it possible to specify multiple types to return from a httpClient's request depending whether the request succeeded (status code 200+) or failed (status code 300-500+)?. This is with JsonFeature configured and the server returning application/json content type.
e
No expert, but from what I've seen, httpClient returns when successful, otherwise it throws an exception, so you need to wrap in a try/catch.
p
something like this?
Copy code
sealed class ApiResponse {
    data class Device(val id: String, val status: String)
    data class Error(val error: String, val message: String, val status: Int)
}

suspend fun fetchDevice(id: String) = client.get<HttpResponse> {
    url {
        takeFrom(baseUri)
        path(id)
    }
}.let {
    when {
        it.status.isSuccess() -> it.receive<ApiResponse.Device>()
        else -> it.receive<ApiResponse.Error>()
    }
}

runBlocking {
    when(val result = fetchDevice("bob")) {
        is ApiResponse.Error -> error("failed to receive device due to: ${result.message}")
        is ApiResponse.Device -> println(result.status)
    }
}
g
Thanks a lot, this was what I was looking for. For this to work, I had to
expectSuccess = false
in the HttpClient config
👍 3