Hey I was wondering how with Ktor-Resources when serializing enums how to catch invalid enum values ...
t
Hey I was wondering how with Ktor-Resources when serializing enums how to catch invalid enum values and handle them in the route? I'd like to just return a 404 not found error instead of it throwing an exception and my error handler catching it and returning a 500
k
Does ktor resources making hanlding serialization different?
Copy code
suspend inline fun <reified T>PipelineContext<Unit, ApplicationCall>.receiveCatching(): Result<T> = try {
    Result.success(call.receive())
} catch (e: Exception) {
    Result.failure(e)
}
t
Well it automatically serializes the enum so I don't need to
so for example
Copy code
@Resource("test") @Serializable
class Resource(
  val e: RandomEnum
)

enum class RandomEnum {
  Test
}
if I call
localhost:8080//test?e=Test
that works
but if I call ?e=TEST that'll throw an error because RandomEnum doesn't have that value and I don't know where to catch it so I can handle the error instead. My temporary solution is just to make the enum a string and parse it myself but if I can have enums automatically parsed and catch the error somewhere in my route I'd prefer that. Well actually the only thing I can think of is to just add a new exception handler for serialization errors.
k
Copy code
suspend inline fun <reified T>PipelineContext<Unit, ApplicationCall>.receiveCatching(): Result<T> = try {
    Result.success(call.receive())
} catch (e: Exception) {
    Result.failure(e)
}

inline fun <reified R : Any> Route.postCatching(
    crossinline body: suspend PipelineContext<Unit, ApplicationCall>.(Result<R>) -> Unit
): Route = postCatching {
    body(receiveCatching<R>())
}

fun Route.postCatching(body: PipelineInterceptor<Unit, ApplicationCall>): Route {
    return method(<http://HttpMethod.Post|HttpMethod.Post>) { handle(body) }
}
would maybe work
postCatching<Resource> { it } it will now be a Result
t
Gotcha, thanks so much.