which returns something like : ```"errors": { "...
# ktor
d
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
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
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
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
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
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
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
Glad I could help 🙂