What is the preferred way of validating query, pat...
# ktor
a
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
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
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)
    }
}
ł
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
@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
trying to validate query parameters with the plugin too
421 Views