How do I log exceptions? I know about <StatusPages...
# ktor
m
How do I log exceptions? I know about StatusPages but I don't really want to change the returned data, I want to log the exception for monitoring purposes.
h
What do you mean? You don't have to change the returned data. But if you throw an exception, what content should be returned?
Copy code
import io.ktor.client.*
import io.ktor.client.request.*
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.cio.*
import io.ktor.server.engine.*
import io.ktor.server.plugins.statuspages.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import kotlinx.coroutines.*

suspend fun main(): Unit = coroutineScope {
    embeddedServer(CIO) {
        install(StatusPages) {
            exception<IllegalStateException> { call, cause ->
                println(cause)
            }
            status(HttpStatusCode(418, "I'm a teapot")) { call, status ->
                println(status)
            }
        }

        routing {
            get {
                call.respondText {
                    "Hello World"
                }
            }
            route("test") {
                get {
                    call.respondText {
                        error("TESTING")
                    }
                }
            }
            get("teapot") {
                call.respond(HttpStatusCode(418, "I'm a teapot"))
            }
            get("tea") {
                call.respondText { HttpClient(io.ktor.client.engine.cio.CIO).get("<http://localhost/teapot>").status.toString() }
            }
        }
    }.start(wait = true)
}
If you call /tea or /teapot the status 418 is printed, but you still get an answer.
m
I'd like to avoid adding another dependency (StatusPages) for the sake of logging an exception but I guess it's not a huge issue
By default KTor returns 500 on exceptions which is fine by me
I guess I could hook into the pipeline (similar to what StatusPages is doing) to log my exceptions
h
Sure, you could do it yourself. Just look at the small plugin (140 lines at all).
👍 1