From 591cd28eb4fddfdb3950fc96c169c8a093e198dd Mon Sep 17 00:00:00 2001 From: DarkCat09 Date: Fri, 21 Jun 2024 16:58:39 +0400 Subject: [PATCH] refactor: cleaner str-to-int with 400 response on err --- src/main/kotlin/su/coolpeople/plugins/Routing.kt | 15 +++------------ 1 file changed, 3 insertions(+), 12 deletions(-) diff --git a/src/main/kotlin/su/coolpeople/plugins/Routing.kt b/src/main/kotlin/su/coolpeople/plugins/Routing.kt index d992ded..1d9ce52 100644 --- a/src/main/kotlin/su/coolpeople/plugins/Routing.kt +++ b/src/main/kotlin/su/coolpeople/plugins/Routing.kt @@ -3,6 +3,7 @@ package su.coolpeople.plugins import io.ktor.server.application.* import io.ktor.server.response.* import io.ktor.server.routing.* +import io.ktor.server.plugins.BadRequestException import io.ktor.http.HttpStatusCode import su.coolpeople.model.ProfileRepository import kotlin.text.toUInt @@ -15,12 +16,7 @@ fun Application.configureRouting() { } get("/{id}") { - val id = try { - call.parameters["id"]!!.toUInt() - } catch (ex: kotlin.NumberFormatException) { - call.respond(HttpStatusCode.BadRequest) - return@get - } + val id = call.parameters["id"]?.toUIntOrNull() ?: throw BadRequestException("Invalid ID") val profile = ProfileRepository.get(id) if (profile == null) { @@ -32,12 +28,7 @@ fun Application.configureRouting() { } delete("/{id}") { - val id = try { - call.parameters["id"]!!.toUInt() - } catch (ex: kotlin.NumberFormatException) { - call.respond(HttpStatusCode.BadRequest) - return@delete - } + val id = call.parameters["id"]?.toUIntOrNull() ?: throw BadRequestException("Invalid ID") if (!ProfileRepository.delete(id)) { call.respond(HttpStatusCode.NotFound)