I’m developing a REST service that uses Ktor. I’m wanting to use call.respondTextWriter to send out json responses. Whenever I run into an error before fully writing the response, I notice that I still get an OK HTTP response code, but the json data I’m writing doesn’t get fully written.
Is there a way to send an error http status code instead of OK if an exception happens inside respondTextWriter?
Expected response:
200 OK
{“response”: [“first”, “second”, “third”]}
When an exception happens:
200 OK
{“response”: [“first”
Exception response I would like:
500 Internal Server Error
“error response”
Example code:
val dataFlow = getDataFlow()
call.respondTextWriter(ContentType.Application.Json, HttpStatusCode.OK) {
withContext(Dispatchers.IO) {
write("{ \"response\": [")
flow
.collectIndexed { index, value ->
val separator = if(index > 0) "," else ""
val writeString = doSomething(value) // Exception may occur here
write("${separator(index)}\"${writeString}\"")
}
write("] }")
}
}