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

dany giguere

02/22/2022, 9:07 PM
which returns something like :
Copy code
"errors": {
   "title": ["The title must contain at least 20 characters"],
   "body": ["The body must contain at least 20 characters"]
}
m

Matthew Gast

02/22/2022, 9:40 PM
Depending on what JSON library you are using, you could use that to manually construct a JSON element with the structure you want and pass that to the response. I know Jackson has mapper.createObjectNode and Kotlinx.serialization also has a way to manually construct a JsonElement.
d

dany giguere

02/22/2022, 9:46 PM
Copy code
mapOf("title" to titleArray, "body" to bodyArray)
returns the json I’m looking for.
I think I’d need to either extend Throwable and add a param with type
Map<String, MutableList<String>>
. But how can I do that properly in Ktor ?
m

Matthew Gast

02/22/2022, 9:50 PM
I guess I'm confused. Are you trying to collate errors? Or are you just trying to create an exception that can be serialized into an error with the desired fields?
d

dany giguere

02/22/2022, 9:51 PM
I would say :
trying to create an exception that can be serialized into an error with the desired fields
It looks like this:
Copy code
if(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))
m

Matthew Gast

02/22/2022, 9:57 PM
So it sounds like you can take two approaches here. One is going to be to create a custom response object and translate the exception values into that:
Copy code
data 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.
d

dany giguere

02/22/2022, 10:14 PM
Thanks a lot for the detailed info. I’m just wondering how am I going to passe the errors so that they will be catchted ??? Here is my demo project if you ever want to check : https://bitbucket.org/danygiguere/ktor_demo/src/master/
Thanks again Matthew. I figured it out !!! 🙂
m

Matthew Gast

02/24/2022, 12:55 AM
Glad I could help 🙂
5 Views