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

Tunji Dahunsi

02/10/2022, 11:05 PM
I’m trying to setup a middleware like chain for processing ktor client errors. Imagine a pipeline of
[ModelValidationHandler, AuthErrorHandler]
and so on. Similar to the
Logging
feature, I’ve implemented my handlers as
HttpClientFeature<*, *>
. The issue I’m having is once one of my handlers reads the
content
ByteReadChannel
of the
HttpResponse
as a
String
, the channel is fully read, and no other Handler can read it. I read the response like this:
Copy code
val observer: ResponseHandler = { response ->
                try {
                    val message = response.content
                            .readRemaining()
                            .readText(charset = response.charset()?: Charsets.UTF_8)
                } catch (_: Throwable) {
                } 
            }

            ResponseObserver.install(ResponseObserver(observer), scope)
The
Logging
feature does not have this limitation. It can log the response, and I can still read it once. Am I consuming the wrong response?
I figured it out, I should be using
HttpResponse.readText()
3 Views