Plugins
- Kotlin course
- Advanced
- Lesson 22/83
- 5 min
Learn ContentNegotiation and StatusPages plugins.
What is a plugin?
A plugin is an add on that changes server behavior. In Ktor it is added with the install call. ContentNegotiation handles JSON, StatusPages catches errors.
Example: install(ContentNegotiation) { json() }. This plugin turns the body into a Kotlin object. With StatusPages the exception<Throwable> { call -> ... } block handles exceptions. Plugins can be installed in the Application module or in the routing block. Configuration happens once; all requests share the same behavior.
Practice Add the ContentNegotiation plugin
Define fun Application.module(). Inside it call install(ContentNegotiation). In main, print println("Plugin added").
Starter code
// Plugin
// write here
import io.ktor.server.application.*
fun main() {
}Sample solution
fun Application.module() {
install(ContentNegotiation)
}
fun main() {
println("Plugin added")
}Expected output
Plugin added
Error handling with StatusPages
StatusPages is the plugin that catches thrown exceptions on the server. install(StatusPages) { exception<Throwable> { call, cause -> call.respondText("Error", status = HttpStatusCode.InternalServerError) } }.
This block catches any exception and returns a consistent error response to the client. Different blocks can be written for specific exception types. StatusPages prevents the app from crashing and handles errors centrally. In production it is used alongside a logging plugin.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the StatusPages plugin do?
- Converts JSON
- Catches errors Correct answer
- Routes URLs
- Picks engine
Explanation: StatusPages handles exceptions.
2 Complete the install call
fun Application.module() {
____(ContentNegotiation) { json() }
}
fun Application.module() {
install(ContentNegotiation) { json() }
}
Explanation: answer: install. Plugins are added with install.
3 Match plugins
| Term | Meaning |
|---|---|
ContentNegotiation |
Converts JSON |
StatusPages |
Catches errors |
install |
Adds plugin |
json() |
Picks format |