dany giguere
04/05/2023, 11:59 PMvalidate<CreatePostRequest> { req ->
var errors = mutableListOf<String>()
if (req.title?.length!! < 4) {
errors.add("title should have at least 4 characters")
}
if (req.body?.length!! < 4) {
errors.add("body should have at least 4 characters")
}
if (errors.isNotEmpty())
ValidationResult.Invalid(errors)
else ValidationResult.Valid
}
which doesn’t work because I have two errors.Aleksei Tirman [JB]
04/06/2023, 7:31 AMvalidate
’s block to carry a necessary information about the errors to the StatusPages
plugin. Here is an example:
fun main() {
embeddedServer(Netty, port = 3333, host = "0.0.0.0") {
install(ContentNegotiation) {
json()
}
install(StatusPages) {
exception<CreatePostRequestValidationException> { call, cause ->
call.respond(status = HttpStatusCode.BadRequest, message = mapOf("errors" to cause.errors))
}
}
install(RequestValidation) {
validate<CreatePostRequest> { req ->
val errors = mutableMapOf<String, String>()
if (req.title?.length!! < 4) {
errors["title"] = "title should have at least 4 characters"
}
if (req.body?.length!! < 4) {
errors["body"] = "body should have at least 4 characters"
}
if (errors.isNotEmpty()) {
throw CreatePostRequestValidationException(errors)
}
ValidationResult.Valid
}
}
routing {
post("/") {
call.receive<CreatePostRequest>()
}
}
}.start(wait = true)
}
dany giguere
04/06/2023, 10:21 PMfun Application.registerValidation() {
? I want to translate my validation messages : https://github.com/danygiguere/ktor_validation/blob/main/src/main/kotlin/com/example/plugins/Validation.kt. I usually get the AccecptLanguage header with
call.request.acceptLanguage()
Aleksei Tirman [JB]
04/07/2023, 6:55 AMStatusPages
plugin where the request can be accessed via the call
object.dany giguere
04/07/2023, 7:12 PM