Kotlin Multiplatform - 使用 Ktor 处理响应 http 代码和异常
Kotlin Multiplatform - Handle response http code and exceptions with Ktor
我刚开始探索 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()
}
}
我已经使用此示例 class(从 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(this@ApplicationApi.address.toString())
}
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}")
}
}
}
}
}
我还测试了 401
和 404
错误。
我刚开始探索 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()
}
}
我已经使用此示例 class(从 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(this@ApplicationApi.address.toString())
}
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}")
}
}
}
}
}
我还测试了 401
和 404
错误。