I am trying to call a Kotlin function that might t...
# ios
m
I am trying to call a Kotlin function that might throw an exception from Swift code. My goal is to retry this operation until it does not throw an exception anymore. To do that, I have added an
@Throws
annotation on the Kotlin side and now wrapped the Swift side with a
Copy code
do {
    try await operation()
} catch let e as NSError {
    ...
}
block. Catching the exception kind of works as I can see logs from inside the catch block, but my app still crashes from the already caught and handled exception, saying that it is uncaught. Why is that happening?
f
e is not an nserror, you have a cast error
m
@François Are you sure? Because the catch block is definitely running and I am operating on that object. For example, this line inside of the catch block works just fine:
NSLog("Exception: \((e.kotlinException as! KotlinThrowable).message)")
prints
App[10692:518585] Exception: Optional("LazyStandaloneCoroutine is cancelling")
f
Ok, fine. What’s the crashlog ?
m
The issue is that I am trying to start a Ktor Server but the port is fixed and sometimes iOS takes some time to clear the port, even after the server and the app are closed. That is why I want to just loop until the port is available again. This results in the Kotlin function I am calling throwing
Copy code
Uncaught Kotlin exception: io.ktor.utils.io.errors.PosixException.AddressAlreadyInUseException: EADDRINUSE (48): Address already in use
which I mostly just want to ignore. But now I have the weird problem that the exception does get caught as my catch blocks are running logic, but the app still crashes with the exception shown above.
f
Oh, I see. I guess the issue is about threads. I don’t know your implementation but check on which thread your exception is throw.
m
Is this shown in the iOS stack trace somewhere?
f
Yes, you can also use Xcode-kotlin https://github.com/touchlab/xcode-kotlin
m
Alright thanks, I will check if I can get this working. But if it turns out that the there are multiple threads involved, is there a way to fix this from the Swift side?
f
No, you can’t fix that on swift. There are api about thread safety on the kotlin side.
m
So basically I have to make sure that I do not run code that might throw an exception on a different thread inside of the Kotlin function?
f
Yes, I guess so.
m
Alright, I will try that. Thanks!