https://kotlinlang.org logo
#ktor
Title
# ktor
a

Arjan van Wieringen

03/23/2023, 10:26 AM
What is the preferred way of validating query, path and headers? Wrapping everything in try/catches is not really DRY in my opinion. For instance, I'd have a UUID as a path parameter. I use UUID.fromString which might fail. I can wrap that with a try/catch and send a response. What is the idiomatic thing of repeatedly handling validation of these parameters?
b

Berkay Özkan

03/23/2023, 11:49 AM
Maybe let it throw exception and handle that exception in StatusPages, responding bad request with explanatory body
Also i use extension methods to get most used parameters like.
call.getDateParam()
j

Johann Pardanaud

03/23/2023, 1:54 PM
For example, with query parameters you can retrieve them with:
Copy code
val value = call.parameters.getOrFail("value")
And you can handle the specific exception with `StatusPages`:
Copy code
install(StatusPages) {
    exception<MissingRequestParameterException> { call, cause ->
        call.respondText("Missing \"${cause.parameterName}\" parameter.", status = HttpStatusCode.BadRequest)
    }
}
ł

Łukasz Nowakowski

03/23/2023, 2:44 PM
maybe this will be useful https://ktor.io/docs/request-validation.html + RequestValidationException
Copy code
install(RequestValidation) {
    validate<String> { bodyText ->
        if (!bodyText.startsWith("Hello"))
            ValidationResult.Invalid("Body text should start with 'Hello'")
        else ValidationResult.Valid
    }
}

install(StatusPages) {
    exception<RequestValidationException> { call, cause ->
        call.respond(HttpStatusCode.BadRequest, cause.reasons.joinToString())
    }
}
a

Arjan van Wieringen

03/23/2023, 5:11 PM
@Johann Pardanaud true, but that doesn’t validate the input. It just checks that there is an input but not that it is a good input. @Łukasz Nowakowski those are for bodies only right? Not for path, query and header parameters? I guess the best solution would be to create extension methods on the call object and have those throw Exceptions
c

Cương Nguyễn

12/16/2023, 6:14 PM
trying to validate query parameters with the plugin too
342 Views