https://kotlinlang.org logo
#ktor
Title
# ktor
s

Stylianos Gakis

10/26/2023, 8:52 PM
Stumbled upon this quite old https://github.com/ktorio/ktor/issues/949 issue regarding doing error handling on ktor clients. Does the suggestion there not suffer from swallowing cancellation exceptions? How does this story look like noawadays? Is the idea still to wrap calls in a try catch but to simply make sure to re-throw in scenarios where the exception is a CancellationException?
c

Christopher Mederos

10/27/2023, 5:13 AM
I use try/catch, but only handle the request related exceptions from the ktor client library (ServerResponseException, HttpRequestTimeoutException, ClientRequestException, etc.). Everything else I just re-throw. I also configure the httpclient with
expectSuccess = true
In practice, I use an
ApiResult<out T : Any>
sealed class and wrap the try/catch logic in a generic
tryResource()
function to streamline my codebase
e

e5l

10/27/2023, 1:11 PM
Hey @Stylianos Gakis, thanks for the question! The described rule (catch all and rethrow cancellation) is good practice. @Viktoriya Nikolova could you please check if we mention this in docs or have it for the kotlinx.coroutines?
👍 1
v

Viktoriya Nikolova

10/27/2023, 1:41 PM
Hi! I see that Exception handling for the HttpClient is explained in the Response validation docs section. Additionally, you might find the HttpRequestRetry plugin helpful, documented in the Retrying failed requests topic.
🙏 1