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

Dusty

03/07/2024, 2:47 PM
Copy code
val userId = (call.principal<JWTPrincipal>()?.payload?.subject?.toIntOrNull() ?: call.respond(HttpStatusCode.BadRequest, mapOf("Response" to NO_USERNAME)))
Is there a way to use the ternary operator to respond to an http request value on value being null? as is this requires it to be cast to Int which obviously isnt going to work or userId declared as Any which also has its own problems. If there is a way to use the ternary operator like this then I could really clean up a lot of the if statements in my route level code. userId will always return an integer so this makes kotlin confused as to what the application calls type is supposed to be
s

Sam

03/07/2024, 2:59 PM
One approach that could work: • Install the
StatusPages
plugin • Create a
BadRequestException
class, and configure the status pages plugin to return a 400 code for that exception • Change your code to throw that exception when there's no user ID.
val userId = (something) ?: throw BadRequestException()
will work, because you can assign the non-existent result of
throw
to anything you like.
d

Dusty

03/07/2024, 3:02 PM
Awesome i will investigate these. Thank you !
a

Aleksei Tirman [JB]

03/08/2024, 8:02 AM
By the way, Ktor already has the
BadRequestException
, which maps to the 400 status code, so you don't need to configure the
StatusPages
plugin.
🙌 1
2 Views