Skip to content

Commit

Permalink
KTOR-5518 Fix Exception type for OkHttp channel adapter (#3394)
Browse files Browse the repository at this point in the history
* KTOR-5518 Make StreamRequestBody throwing only IOException

* KTOR-5518 Keep origin exception type when request is cancelled
  • Loading branch information
e5l authored Feb 10, 2023
1 parent 0712fd4 commit 5600a07
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ private fun mapOkHttpException(
requestData: HttpRequestData,
origin: IOException
): Throwable = when (val cause = origin.unwrapSuppressed()) {
is StreamAdapterIOException -> cause.cause ?: cause
is SocketTimeoutException ->
if (cause.isConnectException()) {
ConnectTimeoutException(requestData, cause)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import io.ktor.utils.io.jvm.javaio.*
import okhttp3.*
import okio.*

internal class StreamAdapterIOException(cause: Throwable) : IOException(cause)

internal class StreamRequestBody(
private val contentLength: Long?,
private val block: () -> ByteReadChannel
Expand All @@ -17,8 +19,14 @@ internal class StreamRequestBody(
override fun contentType(): MediaType? = null

override fun writeTo(sink: BufferedSink) {
block().toInputStream().source().use {
sink.writeAll(it)
try {
block().toInputStream().source().use {
sink.writeAll(it)
}
} catch (cause: IOException) {
throw cause
} catch (cause: Throwable) {
throw StreamAdapterIOException(cause)
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import io.ktor.client.call.*
import io.ktor.client.request.*
import io.ktor.client.tests.utils.*
import io.ktor.http.*
import io.ktor.http.content.*
import io.ktor.network.sockets.*
import io.ktor.server.application.*
import io.ktor.server.cio.*
Expand Down Expand Up @@ -105,4 +106,21 @@ class RequestTests : TestWithKtor() {
assertEquals("OK", response)
}
}

class CustomException : IllegalStateException()

@Test
fun testBodyPropagatesExceptionType() = testWithEngine(OkHttp) {
test { client ->
assertFailsWith<CustomException> {
client.post("$testUrl/echo") {
setBody(object : OutgoingContent.WriteChannelContent() {
override suspend fun writeTo(channel: ByteWriteChannel) {
throw CustomException()
}
})
}.body<String>()
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/*
* Copyright 2014-2023 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/

package io.ktor.client.engine.okhttp

import okio.*
import kotlin.test.*

class StreamRequestBodyTest {

@Test
fun testChannelThrowException() {
val body = StreamRequestBody(0) {
error("Can't read body")
}

assertFailsWith<IOException> {
body.writeTo(Buffer())
}
}
}

0 comments on commit 5600a07

Please sign in to comment.