Hi Everyone, We have a KMP project where we are us...
# ktor
m
Hi Everyone, We have a KMP project where we are using Ktor Client to send HTTP requests. We would like to detect in common code when a request failed because of a network connection issue. How should we do that? During debugging we experienced that e.g. on Android we get a java.net.UnknownHostException. It is important that we would preferably like to solve this in common code. Any help is appreciated!
a
Unfortunately, it's not possible to handle those types of failures in the common code. You can follow the KTOR-2496 for updates.
m
Thank you @Aleksei Tirman [JB]. Is there no workaround either? We were thinking about catching kotlinx IOException for Android and iOS and Throwable for JS
a
You can map platform-specific exception types to your own common exception type.
👍 1
r
my current workaround - probably misses a bunch of cases but still works in most of them iOS
Copy code
override fun isNoConnectionError(e: Throwable): Boolean {
    val nsError = (e as? DarwinHttpRequestException)?.origin
    if (nsError != null) {
        return nsError.domain == NSURLErrorDomain && (nsError.code == NSURLErrorNotConnectedToInternet || nsError.code == NSURLErrorTimedOut || nsError.code == -1004L)
    }
    return when (e) {
        is UnresolvedAddressException -> true
        is SocketTimeoutException -> true
        else -> false
    }
}
android
Copy code
override fun isNoConnectionError(e: Throwable): Boolean {
    return when (e) {
        is UnresolvedAddressException -> true
        is UnknownHostException, is SocketTimeoutException, is ConnectException -> true
        else -> false
    }
}
desktop jvm
Copy code
override fun isNoConnectionError(e: Throwable): Boolean {
    return when (e) {
        is UnresolvedAddressException -> true
        is UnknownHostException, is SocketTimeoutException, is ConnectException -> true
        else -> false
    }
}
wasm
Copy code
override fun isNoConnectionError(e: Throwable): Boolean {
    return when (e) {
        is SocketTimeoutException -> true
        is UnresolvedAddressException -> true
        is kotlinx.io.IOException -> true
        else -> false
    }
}
thank you color 1