我有一個用Ktor制作的API,當請求的某個欄位失敗時,它會回傳500錯誤,我想檢查所有的請求資料并回傳,在這種情況下,422。
Request class:
@Serializable
data class LoginRequest (
val email。字串。
val password: String
)
Routing
route("v1/auth/login"/span>) {
post {
val loginRequest = call.receive<LoginRequest> ()
//LOGIN METHOD。
}
}
現在Ktor顯示的錯誤是:
[eventLoopGroupProxy-4-1] ERROR Application - Unhandled: POST - /v1/auth/login
kotlinx.serialization.MissingFieldException。欄位'password' 是必需的 for 型別與序列名
什么是最好的方法來確保系統不會失敗并以BadRequest作為回應?
uj5u.com熱心網友回復:
如果你想在一個特定的地方捕獲一個例外,你可以使用try/catch:
try {
val loginRequest = call.receive<LoginRequest> ()
...
} catch (e: SerializationException) {
//序列化例外
call.respond(HttpStatusCode.UnprocessableEntity)
} catch (t: Throwable) {
//其他例外。
call.respond(HttpStatusCode.InternalServerError)
}
如果你想要一些全域性的try/catch,Ktor有StatusPages功能用于這種情況:它將在呼叫處理程序中捕獲所有例外。
和try/catch一樣,你可以捕獲一個特定的例外,比如SerializationException,或者使用Exception/Throwable來捕獲任何其他例外。
install(StatusPages) {
exception<SerializationException> { cause ->
//序列化例外。
call.respond(HttpStatusCode.UnprocessableEntity)
}
exception<Throwable> { cause ->
//其他例外
call.respond(HttpStatusCode.InternalServerError)
}
}
uj5u.com熱心網友回復:
你可以用默認的null值使欄位為空,在遇到未知屬性時忽略錯誤,并手動驗證結果物件。下面是一個例子:
import io.ktor.application.*.
import io.ktor.features.*.
import io.ktor.http.*.
import io.ktor.request.*.
import io.ktor.response.*.
import io.ktor.routing.*.
import io.ktor.serialization.*.
import io.ktor.server.engine.*.
import io.ktor.server.netty.*.
import kotlinx.serialization.Serializable.
import kotlinx.serialization.json.Json
@Serializable[/span]。
data class LoginRequest (
val email: = null,
val password: String? = null.
)
suspend fun main() {
embeddedServer(Netty, port = 8080) {
install(ContentNegotiation) {
json(Json {
ignoreUnknownKeys = true"/"/span>) {
val request = call.receive< LoginRequest>()
if (request.email == null || request.password == null) {
call.respond(HttpStatusCode.UnprocessableEntity)
return@post。
}
call.respond(HttpStatusCode.OK)
}
}
}.start()
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/328673.html
標籤:
上一篇:HttpClient回應messege"Theoperationwascanceled."。postman中的json結果是[]?如何從API獲得所有資料
