【问题标题】:How to map ktor response to object depending on response status code如何根据响应状态代码将 ktor 响应映射到对象
【发布时间】:2021-07-07 06:35:31
【问题描述】:

假设我做了一个简单的请求:

get("/getUser/$userId")

结果可能执行成功并返回String 和status=200 或者可能完成并返回status=400 和错误对象:

{
  "errorMessage": "Something went wrong!"
}

我想将所有响应映射到一个公共对象:

data class Response<T>(
  val success: Boolean,
  val result: T,
  val error: Map<String, String>
)

是否有任何可能的解决方案将成功而不是成功结果映射到一个公共对象?

【问题讨论】:

    标签: kotlin ktor


    【解决方案1】:

    您可以拦截HttpResponsePipeline 的Transform 阶段,以便能够将任何响应转换为Response 类型:

    import io.ktor.client.*
    import io.ktor.client.engine.cio.*
    import io.ktor.client.request.*
    import io.ktor.client.statement.*
    import io.ktor.http.*
    
    suspend fun main() {
        val client = HttpClient(CIO) {
            expectSuccess = false
        }
    
        client.responsePipeline.intercept(HttpResponsePipeline.Transform) { (info, body) ->
            val response = when (context.response.status) {
                HttpStatusCode.OK -> Response(success = true, result = body, error = emptyMap())
                HttpStatusCode.BadRequest -> Response(success = false, result = body, error = mapOf("error" to "Some error"))
                else -> error("Cannot map status code ${context.response.status}")
            }
    
            proceedWith(HttpResponseContainer(info, response))
        }
    
        val r = client.get<Response<Any>>("https://httpbin.org/status/400")
        println(r.success)
    }
    

    【讨论】:

      猜你喜欢
      • 2020-08-08
      • 2019-07-22
      • 1970-01-01
      • 2020-01-01
      • 2017-11-03
      • 1970-01-01
      • 1970-01-01
      • 2019-09-30
      • 1970-01-01
      相关资源
      最近更新 更多