[ktor-network/ktor-io question] It seems that `io....
# ktor
d
[ktor-network/ktor-io question] It seems that
io.ktor.utils.io.ByteBufferChannel
reuses the`kotlinx.coroutines.channels.ClosedReceiveChannelException` exception to signal all its EOF errors. It is quite confusing and hard to
catch
when you use both `Channel`s and `ByteBufferChannel`s in the same coroutines. Shouldn't
ByteBufferChannel
use a custom exception inheriting from
IOException
? Should I open a YT issue?
As a workaround, I use the following to wrap operations using a `ByteReadChannel`:
Copy code
internal inline fun <T> ByteReadChannel.wrapExceptions(block: ByteReadChannel.() -> T): T {
    try {
        return block()
    } catch (e: ClosedReceiveChannelException) {
        throw IOException(e.message ?: "Error while reading", e)
    }
}
a
Could you please share a code snippet to reproduce this problem?
d
Hi @Aleksei Tirman [JB] Do you mean a snippet to reproduce the exception sent from
ByteBufferChannel
or a snippet mixing `Channel`s and `ByteReadChannel`s? The latter might be very obscure...
This does throw the
kotlinx.coroutines.channels.ClosedReceiveChannelException
where I would expect an exception unrelated to coroutines:
Copy code
import io.ktor.network.selector.*
import io.ktor.network.sockets.*
import kotlinx.coroutines.*

public suspend fun main(): Unit = coroutineScope {
    val selectorManager = SelectorManager(<http://Dispatchers.IO|Dispatchers.IO>)
    val address = InetSocketAddress("localhost", 9999)

    val serverSocket = aSocket(selectorManager).tcp().bind(address)
    launch {
        val socket = serverSocket.accept()
        socket.close()
    }

    launch {
        val socket = aSocket(selectorManager).tcp().connect(address)
        val readChannel = socket.openReadChannel()
        readChannel.readByte()
    }
}
The said exception stack trace:
Copy code
Exception in thread "main" kotlinx.coroutines.channels.ClosedReceiveChannelException: EOF while 1 bytes expected
	at io.ktor.utils.io.ByteBufferChannel.readByte(ByteBufferChannel.kt:2517)
	at TestByteReadChannelKt$main$2$2.invokeSuspend(TestByteReadChannel.kt:18)
	at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
	at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
	at kotlinx.coroutines.scheduling.CoroutineScheduler.runSafely(CoroutineScheduler.kt:570)
	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.executeTask(CoroutineScheduler.kt:750)
	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.runWorker(CoroutineScheduler.kt:677)
	at kotlinx.coroutines.scheduling.CoroutineScheduler$Worker.run(CoroutineScheduler.kt:664)
a
Thank you. Please file an issue.
👍 1