Ktor for beginners – Status Pages

In the previous lesson we learned how to paginate data returned from our mongodb, in this post we’ll learn about responding with specific errors and pages depending on the status of the request using the Status pages plugin.

for the sake of simplicity im just going to add the video tutorial here with the code snippets as writing the tutorial in addition to doing the recording consumes a lot of time.

Dependencies

find more about the status pages plugin here

implementation("io.ktor:ktor-server-status-pages:$ktor_version")

Usage

fun Application.configureStatusPages(){
    install(StatusPages) {
        handleNotFound()
        exception<Throwable> { call, cause ->
            call.respondText(text = "500: $cause", status = HttpStatusCode.InternalServerError)
        }
    }
}

fun StatusPagesConfig.handleNotFound(){
    status(HttpStatusCode.NotFound){ call, code ->
        // Read request the header
        val acceptHeader = call.request.headers[HttpHeaders.Accept] ?: ""

        // if the accept header contains "text/html" respond with the html page
        if (acceptHeader.contains(ContentType.Text.Html.toString())){
            
            // read the html page from resources
            val page = call.resolveResource("static/error404.html")
            if (page != null){
                call.respond(page)
            }else {
                call.respond(HttpStatusCode.InternalServerError)
            }
            
        } else {
            // respond with a json
            call.respond(code, SimpleResponse(false, "Sorry the page you're looking for is not found :("))
        }
    }
}

The source code can be found here

0 0 votes
Article Rating
Subscribe
Notify of
guest

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments

[…] the previous lesson we learned how to customize status pages in our server, in this post we’ll learn about request […]