1

Let's say I have a Request data class:

data class Request(
   val firstName: String,
   val lastName: String
)

which I want to serialize when getting to a specific api route. Using Ktor, it would look like this:

call.receive<Request>()

This would work perfectly if I get a valid json such as { "firstName: "TestFirst", "lastName": "TestLast" }

But, what if we get a json object or array instead of the expected string? { "firstName: [], "lastName": {} }?

The library would throw an exception and I wouldn't be able to know we had two different validation problems:

  1. firstName must be a valid string (and not an array)
  2. lastName must be a valid string (and not an object).

How can I find these errors so that I would be able to map them nicely back to the user in the rest api response?

Ofek
  • 324
  • 3
  • 13
  • Shouldn't just the framework return 400 Bad request? – Some random IT boy Sep 25 '22 at 16:20
  • Yes, but also a list of all the validation errors so the end user know what went wrong. That's my main problem. Thanks. – Ofek Sep 26 '22 at 17:18
  • AFAIK there is no way of collecting all errors and no way of getting structured information about those errors, but only by the message of an exception. – Aleksei Tirman Sep 27 '22 at 09:23
  • Probably, the problem is that it will throw one error. Maybe I have a solution but it's not very elegant. I Could try and receive and then manually looking if it's matching the type, validation, etc.. Thanks anyways – Ofek Sep 28 '22 at 10:24
  • I think this issue is related: https://github.com/Kotlin/kotlinx.serialization/issues/1930 – aSemy Oct 09 '22 at 11:48
  • Yep, thank you very much. Let's hope they add something like this. @aSemy what's your alternative for now? I have a nice idea but it's pretty boilerplate.. – Ofek Oct 10 '22 at 12:12

0 Answers0