Ktor - Error Handling for respondTextWriter

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\": [")
            .collectIndexed { index, value ->
				val separator = if(index > 0) "," else ""
				val writeString = doSomething(value) // Exception may occur here
        write("] }")

I guess the main point of using text writer is to stream the data, so send it while it is being written. You can’t undo what has been already sent.

If you need to make sure that you can create the data successfully then first create a resulting string and then send it.