From dad0d524a20c910d5101f76b11cfad86c87ef1c0 Mon Sep 17 00:00:00 2001 From: Aliothmoon Date: Wed, 8 Jan 2025 00:44:46 +0800 Subject: [PATCH] feat: improve the response code --- src/main/kotlin/biz/devloper.kt | 2 +- src/main/kotlin/exception/ex.kt | 4 +--- src/main/kotlin/router/router.kt | 3 ++- src/main/kotlin/utils/util.kt | 4 ++-- 4 files changed, 6 insertions(+), 7 deletions(-) diff --git a/src/main/kotlin/biz/devloper.kt b/src/main/kotlin/biz/devloper.kt index ca40110..aed7a88 100644 --- a/src/main/kotlin/biz/devloper.kt +++ b/src/main/kotlin/biz/devloper.kt @@ -16,7 +16,7 @@ import java.util.* * @return [Resp] */ fun validateToken(token: String?): Resp { - val tk = token.throwIfNullOrEmpty("Token不能为空") + val tk = token.throwIfNullOrEmpty("Token不能为空", 400) val qr = DB.from(ApplicationToken) .select(ApplicationToken.status, ApplicationToken.id) .where { diff --git a/src/main/kotlin/exception/ex.kt b/src/main/kotlin/exception/ex.kt index 84d81af..bcdcacb 100644 --- a/src/main/kotlin/exception/ex.kt +++ b/src/main/kotlin/exception/ex.kt @@ -1,8 +1,6 @@ package exception -class ServiceException : RuntimeException { - constructor(message: String?) : super(message) - constructor() : super() +class ServiceException(message: String?, val code: Int = 200) : RuntimeException(message) { override fun fillInStackTrace() = this } \ No newline at end of file diff --git a/src/main/kotlin/router/router.kt b/src/main/kotlin/router/router.kt index d6ed656..cfe9761 100644 --- a/src/main/kotlin/router/router.kt +++ b/src/main/kotlin/router/router.kt @@ -39,12 +39,13 @@ private fun errHandler(ctx: RoutingContext) { val ex = ctx.failure() val resp = ctx.response() resp.putHeader("Content-Type", "application/json") - resp.setStatusCode(500) if (ex is ServiceException) { + ctx.response().setStatusCode(ex.code) ctx.end(Resp.fail(ex.message).toJson()) log.error("ServiceException {}", ex.message) return } + resp.setStatusCode(500) log.error("unexpected error ", ex) ctx.end(UEE) } diff --git a/src/main/kotlin/utils/util.kt b/src/main/kotlin/utils/util.kt index e0e6e75..95dc9de 100644 --- a/src/main/kotlin/utils/util.kt +++ b/src/main/kotlin/utils/util.kt @@ -10,9 +10,9 @@ fun Boolean.throwIf(msg: String) { } } -fun T?.throwIfNullOrEmpty(msg: String): T { +fun T?.throwIfNullOrEmpty(msg: String, code: Int = 200): T { if (this == null || (this is String && this.isEmpty())) { - throw ServiceException(msg) + throw ServiceException(msg, code) } return this }