gpt4 book ai didi

ktor - Kotlin Multiplatform - 使用 Ktor 处理响应 http 代码和异常

转载 作者:行者123 更新时间:2023-12-02 19:15:06 55 4
gpt4 key购买 nike

我刚刚开始探索 KMM,到目前为止看起来确实不错。

基本上,我想要在一个地方全局处理所有 http 错误代码(如 401、404、500)。

但是,我不确定如何与响应交互。

我在 HttpClient 中安装了 ResponseObserver,但只有当 http 状态为 200 时它才会出现。

我也尝试过使用HttpResponseValidator,但它永远不会去那里。

代码如下:

class ApiImpl : Api {

private val httpClient = HttpClient {

install(JsonFeature) {

val json = kotlinx.serialization.json.Json { ignoreUnknownKeys = true }

serializer = KotlinxSerializer(json)
}

install(ResponseObserver) {

onResponse { response ->

//*** We get here only if http status code is 200 ***/

println("HTTP status: ${response.status.value}")
}
}

HttpResponseValidator {

validateResponse { response: HttpResponse ->

val statusCode = response.status.value

//*** We never get here ***/

println("HTTP status: $statusCode")

when (statusCode) {

in 300..399 -> throw RedirectResponseException(response)
in 400..499 -> throw ClientRequestException(response)
in 500..599 -> throw ServerResponseException(response)
}

if (statusCode >= 600) {
throw ResponseException(response)
}
}

handleResponseException { cause: Throwable ->

throw cause
}
}
}

override suspend fun getUsers(): List<User> {

try {

return httpClient.get("some url....")

} catch (e: Exception) {

//*** We get here in case of 404 (for example), but I don't want to repeat it in every request ***/

println(e.message)
}

return emptyList()
}
}

最佳答案

我已经使用此示例类(从 official ktor github rep 获取并修改)测试了您的场景,并且我可以命中您想要获取错误代码的所有断点(例如 500)

package com.example.kmmtest001.shared

import io.ktor.client.*
import io.ktor.client.features.*
import io.ktor.client.features.json.*
import io.ktor.client.features.json.serializer.*
import io.ktor.client.features.observer.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import kotlinx.coroutines.*

internal expect val ApplicationDispatcher: CoroutineDispatcher

class ApplicationApi {
private val client = HttpClient {
install(JsonFeature) {
val json = kotlinx.serialization.json.Json { ignoreUnknownKeys = true }
serializer = KotlinxSerializer(json)
}

install(ResponseObserver) {
onResponse { response ->
println("HTTP status: ${response.status.value}")
}
}

HttpResponseValidator {
validateResponse { response: HttpResponse ->
val statusCode = response.status.value

println("HTTP status: $statusCode")

when (statusCode) {
in 300..399 -> throw RedirectResponseException(response)
in 400..499 -> throw ClientRequestException(response)
in 500..599 -> throw ServerResponseException(response)
}

if (statusCode >= 600) {
throw ResponseException(response)
}
}

handleResponseException { cause: Throwable ->
throw cause
}
}
}

var address = Url("https://tools.ietf.org/rfc/rfc1866.txt")

fun about(callback: (String) -> Unit) {
GlobalScope.apply {
launch(ApplicationDispatcher) {
val result: String = client.get {
url(<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="05716d6c7645447575696c6664716c6a6b44756c2b646161776076762b716a5671776c6b62" rel="noreferrer noopener nofollow">[email protected]</a>())
}

callback(result)
}
}
}

fun get500ServerError(callback: (String) -> Unit) {
GlobalScope.apply {
launch(ApplicationDispatcher) {
try {
val result: String = client.get {
url("https://www.versionestabile.it/_sw/so/63812313/index500.php")
}

callback(result)
} catch (se: ServerResponseException) {
val statusCode = se.response?.status?.value
callback("HTTP status code: $statusCode --> ${se.message}")
} catch (ce: ClientRequestException) {
val statusCode = ce.response?.status?.value
callback("HTTP status code: $statusCode --> ${ce.message}")
}
}
}
}
}

enter image description here

enter image description here

我还测试了 401404 错误。

enter image description here

enter image description here

关于ktor - Kotlin Multiplatform - 使用 Ktor 处理响应 http 代码和异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63812313/

55 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com