A bit of an00b question regarding `suspend` functi...
# multiplatform
b
A bit of an00b question regarding
suspend
functions and Swift ... Note: I'm using SKIE in my project. So, if i have a basic suspend function:
Copy code
suspend fun doStuff(value: int) {
   delay(100.milliseconds)
   print("Did stuff with $value!)
}
I know the Swift side will get a cancelation error if the task/coroutine is canceled. And I can handle the error as an optional value in Swift, in order to "ignore" the cancelation exception:
Copy code
Task {
   try? await doStuff()
}
So far so good. But say my suspend function can throw some "custom" exception (other than a cancelation exception). I want the Swift side to have to handle that error, but it would be nice if it could still "ignore" the cancelation exception. Is there some way I can do that? Could I annotate my suspend function with
@Throws()
and only specify my "custom" exception?
Copy code
@Throws(IllegalArgumentException::class)
suspend fun doStuff(value: int) {
   delay(100.milliseconds)
   if (value < 0) { throw IllegalArgumentException("Value must be greater than 0") }
   print("Did stuff with $value!)
}
Or, maybe I'm misunderstanding the whole thing entirely.
s
I'm not really familiar with how this can be handled, but have you tried wrapping the possible results of the suspending function? Something similar to the
Result
class so you don't deal with Exceptions, but instead deal with an
Error
type and a
Success
type
p
#swift-export maybe
t
Copy code
do {
  return try await doStuff()
} catch is CancellationError {
  return nil
} catch {
  // handle 'error' here
}
This is one way to do it. But this sounds like something that could make a SKIE annotation. Something like
@NullOnCancelled
and
@UnsafeCancellation
where the first one would make your return type optional for Swift and return nil on cancellation and the second allowing you to handle cancellation yourself and crash if encountered