Hi, the WebSocket plugin throws a `WebSocketExcept...
# ktor
s
Hi, the WebSocket plugin throws a
WebSocketException
if the response code is not 101. https://github.com/ktorio/ktor/blob/main/ktor-client/ktor-client-core/common/src/io/ktor/client/plugins/websocket/WebSockets.kt#L202 Is there any way to somehow get the original response from the server?
a
The only way to get the response object when the
WebSocketException
is thrown is by intercepting the earlier phase of the response pipeline. Here is an example:
Copy code
val client = HttpClient(CIO) {
    install(WebSockets)
}

client.responsePipeline.intercept(HttpResponsePipeline.Parse) { (info, session) ->
    try {
        proceed()
    } catch (cause: WebSocketException) {
        println(context.response)
        throw cause
    }
}

client.webSocket("<ws://httpbin.org/status/404>") {}
s
Thanks for the quick reply and solution @Aleksei Tirman [JB]. When I try to decode the response body using
context.response.body()
, it causes a stackoverflow, because of
client.responsePipeline.execute(this, subject).response.takeIf { it != NullBody }
being called inside. Is there a way around it? I ended up doing
context.response.rawContent.run { peek(availableForRead)?.decodeToString() }
, but since
rawContent
is an internal api, it'd be better to avoid it.
a
The only way I see is to access the
rawContent
.
👍 1