What is the recommended way for validations in kto...
# ktor
h
What is the recommended way for validations in ktor? I have always used `javax.validation`and it is very easy and gets out of your way even if the annotations look a bit ugly. Writing validation functions for each and every requests field seems very messy. Is that really how we want to do it? Why not stick with annotations and the validation plugin use them much like
javax.validation
. That way the restrictions on the request type stays very close to the type and it becomes very little code.
a
If you mean a request body validation then the recommended way is to use the RequestValidation plugin.
c
If you use KotlinX.Serialization, you can use
require
in your constructors.
Copy code
@Serializable
data class Password(
    val text: String,
) {
    init {
        require(text.length > 8) { "The password is too short" }
    }
}
Copy code
post("setPassword") {
    val password = body.receive<Password>()
}
👍 1
h
We do use kotlinx.serialization and that seems a very attractive way to accomplish it
The RequestValidation plugin is what I mean @Aleksei Tirman [JB] that becomes verbose and disconnected to the code if I understand it's usage correctly. It could parse annotations instead of forcing a chunk of code in the plugin block
👍 1
s
require
in init blocks is great for enforcing invariants, but if deserialization fails one of the checks ktor emits a "BadRequestException" with the require message suppressed. The only way I've found to pass the particulars of the failure back to the caller is by capturing the exception with a status page and using Internal api rootCause. Do we have a more stable way to support invariants?
c
Using StatusPages to catch deserialization errors is the recommended practice. I'm not sure why you need rootCause, the throwable's string explains what the problem is?
s
cause.message
? You get something akin to
Failed to convert request body to class com.jetbrains.Password
Which, while true, doesn't give helpful feedback to the caller. In the same way as
"The password is too short"
does if you use
cause.rootCause
Sorry if I'm missing something obvious here—
c
I'm surprised, I seem to remember the message being fairly clear
h
We are very happy with the StatusPages plugin actually after having added it. Makes it clean and centralized and we can easily switch status code in some special cases.
👍 2
885 Views