Hi ! I would like to know how can I check if there...
# ktor
d
Hi ! I would like to know how can I check if there is a response body before reading it For example, from an API, I have this response:
Copy code
COMMON HEADERS
-> Cache-Control: no-store
-> Content-Length: 0
-> Content-Type: application/json
-> Date: Tue, 21 Nov 2023 21:40:39 GMT
-> Strict-Transport-Security: max-age=31536000; includeSubDomains
BODY Content-Type: application/json
BODY START

BODY END
The body is empty, so when I try to read it, my code throws an exception and I would like to avoid that. Do you know how can I check if the response has a body or not ?
1
b
Maybe you can check
Copy code
call.receiveNullable
d
I'm using Ktor as a client and not server. Also, I'm using a HttpResponseValidator
Copy code
HttpResponseValidator {
                validateResponse { response ->
                    if (!response.status.isSuccess()) {
                        // Get body here
                    }
                }
            }
A try catch works of course, but I don't know if there is a better approach
b
Oh sorry i read as request. is response always null? or depends on condition status code etc
m
capture your response in a Result and check the result example
Copy code
suspend fun getNodeInfo(instance: String): Result<NodeInfo> = runCatching {
        lenientKtor
            .get("${constructBaseUrl(instance)}/nodeinfo/2.0.json")
            .body<NodeInfo>()
    }

suspend fun someOther(){
   val node = getNodeInfo(instance)
   if(node.isSuccess) { ... }
}
d
The response is arbitrary. With always a different format so that's a bit annoying Well according to the MV response, I'm supposing that Result / try catch is the only solution
m
It certianly isnt the only solution
With always a different format so that's a bit annoying
what do you mean with that? Do you mean you always get unkown json structure? You can read the body as a generic JsonObject and parse that
d
Exactly, for the moment, I detected three type of response body: • Nothing (my current question) •
Copy code
{data:{error: <message>}}
Copy code
{errors: [list of message]}
a
Unfortunately, you cannot determine whether response empty or not without reading it.
d
I'm agree with that, but in this case, maybe the
bodyAsText
should returns empty string instead of throw an illegalStateException 🤔
a
Can you share the exception message and stack trace?
d
OK I will send that during the day 👍
Aaah no .. finally I have an empty string .. Well I don't know why yesterday I had an IllegalState