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

Posted

技术标签:

【中文标题】Kotlin Multiplatform - 使用 Ktor 处理响应 http 代码和异常【英文标题】:Kotlin Multiplatform - Handle response http code and exceptions with Ktor 【发布时间】: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 的原因。 【参考方案1】:

我已经用这个示例类(从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")
                
            
        
    

我还测试了401404 错误。

【讨论】:

以上是关于Kotlin Multiplatform - 使用 Ktor 处理响应 http 代码和异常的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Kotlin Multiplatform(纯 kotlin)中进行延迟

在 Kotlin Multiplatform 中使用 Swift 协议默认实现

Kotlin Multiplatform Cocoapods 集成问题

如何使用 Cocoapods 调整 Kotlin Multiplatform 项目的 Swift 类名?

Kotlin-Multiplatform 中的 CPointer

Kotlin-multiplatform:如何执行 iOS 单元测试