gpt4 book ai didi

kotlin - 在 HttpClient Ktor 中处理异常

转载 作者:行者123 更新时间:2023-12-04 14:48:44 25 4
gpt4 key购买 nike

我在下面的通用模块中编写了通用代码并在 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 不起作用

最佳答案

对当前答案没有增加太多,但为了回应 CVS 的评论,我一直在使用以下内容在我的应用程序中添加 ktor 客户端错误处理。它利用了 Result应用程序接口(interface)。 runCatching {}一网打尽Throwable s,您可以调整 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
}
}
)
我敢肯定它可以做得更整洁,但这是迄今为止我想出的最好的。

关于kotlin - 在 HttpClient Ktor 中处理异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54679592/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com