Hi everyone, I'm running into a weird issue and I'...
# ktor
d
Hi everyone, I'm running into a weird issue and I'm wondering if anyone can point in the right direction - we are using Ktor client to talk to a backend built by another team and backend responds with 401 in some cases but I have a feeling it returns a malformed response which results in
io.ktor.utils.io.ClosedByteChannelException
on our client. More details in thread
This is the response we get that throws that Ktor exception:
Copy code
:status: 401
date: Fri, 21 Nov 2025 19:30:09 GMT
content-type: application/json
alt-svc: h3=":443";ma=86400,h3-29=":443";ma=86400,h3-27=":443";ma=86400
cache-control: no-store
content-encoding: gzip
vary: Accept-Encoding
via: 1.1 varnish,1.1 varnish
x-content-type-options: nosniff
strict-transport-security: max-age=31536000; includeSubDomains; preload
x-cache: CONFIG_NOCACHE
x-cache-hits: 0,0
one thing that stands out is that there is no
content-length: 0
header, is that really what will be causing this exception? Is that header required?
We are very early days so our HttpClientConfig is pretty simple, i.e. only this:
Copy code
val defaultTimeout = 30.seconds.inWholeMilliseconds

        install(HttpTimeout) {
            requestTimeoutMillis = defaultTimeout
            connectTimeoutMillis = defaultTimeout
            socketTimeoutMillis = defaultTimeout
        }

        install(ContentNegotiation) {
            json(Json {
                ignoreUnknownKeys = true
            })
        }

        install(Resources)

        defaultRequest {
            url("...")
        }
Is there anything that I can do on the client side for this? Using a response exception validator like in the docs
Copy code
expectSuccess = true
        HttpResponseValidator {
            handleResponseExceptionWithRequest { exception, request ->
                val clientException = exception as? ClientRequestException ?: return@handleResponseExceptionWithRequest
                val exceptionResponse = clientException.response
                ...
            }
        }
Does not really help either because if I catch
ClosedByteChannelException
instead of
ClientRequestException
I can't do anything meaningful with it as I won't have access to the
HttpResponse
(or it's status code at least) and I don't think I should assume that
ClosedByteChannelException
means 401 specifically...
a
By the stacktrace of the exception caused the
ClosedByteChannelException
, you can determine where the channel was closed.
d
The stacktrace is this, not sure where to start digging from it tho
Copy code
io.ktor.utils.io.ClosedByteChannelException
  	at io.ktor.utils.io.CloseToken$wrapCause$1.invoke(CloseToken.kt:16)
  	at io.ktor.utils.io.CloseToken$wrapCause$1.invoke(CloseToken.kt:16)
  	at io.ktor.utils.io.CloseToken.wrapCause(CloseToken.kt:21)
  	at io.ktor.utils.io.CloseToken.wrapCause$default(CloseToken.kt:16)
  	at io.ktor.utils.io.ByteChannel.getClosedCause(ByteChannel.kt:61)
  	at io.ktor.utils.io.ByteReadChannelOperationsKt.rethrowCloseCauseIfNeeded(ByteReadChannelOperations.kt:544)
  	at io.ktor.utils.io.ByteReadChannelOperationsKt.readRemaining(ByteReadChannelOperations.kt:222)
  	at io.ktor.client.call.SavedCallKt.save(SavedCall.kt:38)
  	at io.ktor.client.plugins.DoubleReceivePluginKt$SaveBody$1$1.invokeSuspend(SaveBody.kt:45)
  	at io.ktor.client.plugins.DoubleReceivePluginKt$SaveBody$1$1.invoke(Unknown Source:11)
  	at io.ktor.client.plugins.DoubleReceivePluginKt$SaveBody$1$1.invoke(Unknown Source:6)
  	at io.ktor.util.pipeline.DebugPipelineContext.proceedLoop(DebugPipelineContext.kt:79)
  	at io.ktor.util.pipeline.DebugPipelineContext.proceed(DebugPipelineContext.kt:57)
  	at io.ktor.util.pipeline.DebugPipelineContext.execute$ktor_utils(DebugPipelineContext.kt:63)
  	at io.ktor.util.pipeline.Pipeline.execute(Pipeline.kt:92)
  	at io.ktor.client.HttpClient$2.invokeSuspend(HttpClient.kt:1367)
  	at io.ktor.client.HttpClient$2.invoke(Unknown Source:13)
  	at io.ktor.client.HttpClient$2.invoke(Unknown Source:4)
  	at io.ktor.util.pipeline.DebugPipelineContext.proceedLoop(DebugPipelineContext.kt:79)
  	at io.ktor.util.pipeline.DebugPipelineContext.proceed(DebugPipelineContext.kt:57)
  	at io.ktor.util.pipeline.DebugPipelineContext.proceedWith(DebugPipelineContext.kt:42)
  	at io.ktor.client.engine.HttpClientEngine$install$1.invokeSuspend(HttpClientEngine.kt:166)
  	at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:34)
  	at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:100)
  	at android.os.Handler.handleCallback(Handler.java:1041)
  	at android.os.Handler.dispatchMessage(Handler.java:103)
  	at android.os.Looper.dispatchMessage(Looper.java:315)
  	at android.os.Looper.loopOnce(Looper.java:251)
  	at android.os.Looper.loop(Looper.java:349)
  	at android.app.ActivityThread.main(ActivityThread.java:9041)
  	at java.lang.reflect.Method.invoke(Native Method)
  	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:593)
  	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:929)
  Caused by: java.io.EOFException
  	at okio.RealBufferedSource.require(RealBufferedSource.kt:225)
  	at okio.GzipSource.consumeHeader(GzipSource.kt:102)
  	at okio.GzipSource.read(GzipSource.kt:60)
  	at okio.RealBufferedSource.read(RealBufferedSource.kt:85)
  	at io.ktor.client.engine.okhttp.OkHttpEngineKt$toChannel$1.invokeSuspend$lambda$0$0(OkHttpEngine.kt:166)
  	at io.ktor.client.engine.okhttp.OkHttpEngineKt$toChannel$1.$r8$lambda$82aJV-caE7f-evd5GVB0A8b1QLk(Unknown Source:0)
  	at io.ktor.client.engine.okhttp.OkHttpEngineKt$toChannel$1$$ExternalSyntheticLambda0.invoke(D8$$SyntheticClass:0)
  	at io.ktor.utils.io.ByteWriteChannelOperations_jvmKt.write(ByteWriteChannelOperations.jvm.kt:28)
  	at io.ktor.utils.io.ByteWriteChannelOperations_jvmKt.write$default(ByteWriteChannelOperations.jvm.kt:25)
  	at io.ktor.client.engine.okhttp.OkHttpEngineKt$toChannel$1.invokeSuspend(OkHttpEngine.kt:164)
  	at io.ktor.client.engine.okhttp.OkHttpEngineKt$toChannel$1.invoke(Unknown Source:8)
  	at io.ktor.client.engine.okhttp.OkHttpEngineKt$toChannel$1.invoke(Unknown Source:4)
  	at io.ktor.utils.io.ByteWriteChannelOperationsKt$writer$job$1.invokeSuspend(ByteWriteChannelOperations.kt:185)
  	at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:34)
  	at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:100)
  	at kotlinx.coroutines.internal.LimitedDispatcher$Worker.run(LimitedDispatcher.kt:124)
  	at kotlinx.coroutines.scheduling.TaskImpl.run(Tasks.kt:89)
  	at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:586)
  	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:820)
  	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:717)
  	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:704)
Actually I think I see the problem - the response has
content-encoding: gzip
so I'll need to install the
ContentEncoding
plugin. Kinda surprised by the behaviour given there's no content really but 🤷. Thanks Aleksei !
119 Views