https://kotlinlang.org logo
#ktor
Title
# ktor
g

Grantas33

04/30/2020, 1:06 PM
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

Eamonn

04/30/2020, 1:51 PM
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

phldavies

04/30/2020, 3:13 PM
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

Grantas33

04/30/2020, 3:35 PM
Thanks a lot, this was what I was looking for. For this to work, I had to
expectSuccess = false
in the HttpClient config
👍 3
4 Views