dany giguere
02/22/2022, 9:07 PM"errors": {
"title": ["The title must contain at least 20 characters"],
"body": ["The body must contain at least 20 characters"]
}
Matthew Gast
02/22/2022, 9:40 PMdany giguere
02/22/2022, 9:46 PMmapOf("title" to titleArray, "body" to bodyArray)
returns the json I’m looking for.dany giguere
02/22/2022, 9:47 PMMap<String, MutableList<String>>
. But how can I do that properly in Ktor ?Matthew Gast
02/22/2022, 9:50 PMdany giguere
02/22/2022, 9:51 PMtrying to create an exception that can be serialized into an error with the desired fields
dany giguere
02/22/2022, 9:52 PMif(payload.body.length < 20) {
bodyArray.add("The body must contain at least 20 characters")
}
if (titleArray.size > 0) {
throw UnprocessableEntityException(mapOf("title" to titleArray, "body" to bodyArray))
Matthew Gast
02/22/2022, 9:57 PMdata class ErrorContainer(val errors: Map<String, List<String>>)
Or you can manually construct the JSON object using the facilities provided by the JSON library you are using. Once you have that object, you should be able to use call.respond(HttpStatusCode.UnprocessableEntity, errorContainer)
like you would any other response you would want to serialize.
I wouldn't recommend directly responding with the exception as you will probably end up with a bunch of other fields you don't want exposed.dany giguere
02/22/2022, 10:14 PMdany giguere
02/23/2022, 9:46 PMMatthew Gast
02/24/2022, 12:55 AM