如何在ktor中获取api调用响应中的错误消息



我正在学习汉语。我想打印错误值或异常。我从这篇文章中截取了一些代码。我没有完全理解这个帖子的答案。

ApiResponse.kt

sealed class ApiResponse<out T : Any> {
data class Success<out T : Any>(
val data: T?
) : ApiResponse<T>()
data class Error(
val responseCode: Int = -1,
) : ApiResponse<Nothing>()
fun handleResult(onSuccess: ((responseData: T?) -> Unit)?, onError: ((error: Error) -> Unit)?) {
when (this) {
is Success -> {
onSuccess?.invoke(this.data)
}
is Error -> {
onError?.invoke(this)
}
}
}
}
@Serializable
data class ErrorResponse(
var errorCode: Int = 1,
val errorMessage: String = "Something went wrong"
)

KtorApi.kt

class KtorApi(private val httpClient: HttpClient) : NetworkRoute() {
suspend fun getCat(): Response<CatResponse> {
val response = httpClient.get {
url("https://xyz/cat")
}
return apiCall(response)
}
}

CatResponse.kt

@Serializable
data class CatResponse(
val items: List<CatDetails>? = null
)
@Serializable
data class CatDetails(
val id: String? = null,
val name: String? = null,
)

ViewModel.kt

fun getCat() {
viewModelScope.launch {
KtorApi.getCat().handleResult({ data ->
logE("Success on cat api response->>> $data")
}) { error ->
logE("Error on cat api ->>>> $error ")
}
}
}

在这里,我已经成功地从Success获得数据,但我不知道如何在错误中获得错误或异常。

actual fun httpClient(config: HttpClientConfig<*>.() -> Unit) = HttpClient(OkHttp) {
config(this)
install(Logging) {
logger = Logger.SIMPLE
level = LogLevel.BODY
}
expectSuccess = false
install(ContentNegotiation) {
json(Json {
prettyPrint = true
ignoreUnknownKeys = true
explicitNulls = false
})
}
}     

如何在error数据类中传递异常或错误代码、状态、正文?有人知道吗?

对于kotlin挂起函数,您需要使用try/catch块来捕获错误:

val apiResponse = try {
ApiResponse.Success(KtorApi.getCat())
} catch (e: ClientRequestException) {
ApiResponse.Error(e.response.status)
} catch (e: Exeption) {
// some other error
ApiResponse.Error()
}

最新更新