```val userId = (call.principal<JWTPrincipal>()?.p...
# ktor
d
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
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
Awesome i will investigate these. Thank you !
a
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