【发布时间】:2020-12-27 22:13:24
【问题描述】:
我刚开始探索 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()
}
}
【问题讨论】:
-
你在你的HttpClient中设置
expectSuccess = false了吗?这可能是您在 ResponseObserver/Validator 中仅获得 200 的原因。