【问题标题】:Handling Exception in HttpClient Ktor处理 HttpClient Ktor 中的异常
【发布时间】:2019-07-07 20:12:07
【问题描述】:

我在下面的一个通用模块中编写了一个通用代码并在JS环境中测试

val response = client.post<HttpResponse>(url) {
    body = TextContent("""{"a":1,"b":2}""", ContentType.Application.Json)
}
if (response.status != HttpStatusCode.OK) {
    logger.error("Error, this one failed bad?")
}

但我的代码在 client.post 结束,并在没有网络上取消了 corutineException。我该如何处理这个和任何其他异常?如果有互联网连接。没有什么失败,我希望能够处理异常。如何?

注意:try,catch 不起作用

【问题讨论】:

    标签: kotlin ktor kotlin-multiplatform


    【解决方案1】:

    目前的答案并没有增加太多,但为了回应 CVS 的评论,我一直在使用以下内容在我的应用程序中添加 ktor 客户端错误处理。它使用Result API。 runCatching {} 捕获所有 Throwables,您可以调整 getOrElse 块的行为以捕获您感兴趣的异常。

    suspend fun <T> HttpClient.requestAndCatch(
        block: suspend HttpClient.() -> T,
        errorHandler: suspend ResponseException.() -> T
    ): T = runCatching { block() }
        .getOrElse {
            when (it) {
                is ResponseException -> it.errorHandler()
                else -> throw it
            }
        }
    
    // Example call
    client.requestAndCatch(
        { get<String>("/") },
        {
            when (response.status) {
                HttpStatusCode.BadRequest -> {} // Throw errors or transform to T 
                HttpStatusCode.Conflict -> {}
                else -> throw this
            }
        }
    )
    

    我确信它可以变得更整洁,但这是迄今为止我想出的最好的。

    【讨论】:

      【解决方案2】:

      好在到处问了之后,我得到了github issues的帮助,来到了这个工作区

      try {
          val response = client.post<HttpResponse>(url) {
              body = TextContent("""{"a":1,"b":2}""", ContentType.Application.Json)
          }
          if (response.status != HttpStatusCode.OK) {
              logger.error("Error, this one failed bad?")
          }
      } catch (cause: Throwable) {
          logger.error("Catch your error here")
      }
      

      不要将catch (c: Throwable)catch (e: Exception) 混淆

      希望对你有帮助

      【讨论】:

      • 包装这个 try-catch 块的惯用方式是什么?也许某种内联函数?
      • 您如何区分网络故障(您可以向用户显示但否则忽略)与指示某些内容已损坏的错误(例如使用 KotlinxSerializer 响应时的反序列化错误)和应该发送到崩溃报告工具?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-02
      • 2020-12-27
      • 2020-06-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多