I have the following method returning Flow
@Throws(Throwable::class) fun getPokemon(): Flow<PokemonList> {
try {
return flow {
throw Exception("Hello")
emit(api.getFirstPagePokedex())
}
} catch (e: Throwable) {
throw e
}
}
where api.getFirstPagePokedex is a suspend fun with signature suspend fun getFirstPagePokedex(): PokemonList
.
When I call getPokemon()
in Swift, I'm faced with this error
Exception doesn't match @Throws-specified class list and thus isn't propagated from Kotlin to Objective-C/Swift as NSError.
It is considered unexpected and unhandled instead. Program will be terminated.
Uncaught Kotlin exception: kotlin.Exception: Hello
If I move throw Exception("Hello")
outside flow block then the iOS version works fine. But it would not catch the error from api.getFirstPagePokedex()
as it should.
@Throws(Throwable::class) fun getPokemon(): Flow<PokemonList> {
try {
throw Exception("Hello")
return flow {
emit(api.getFirstPagePokedex())
}
} catch (e: Throwable) {
throw e
}
}
How can we catch exception from flow
block correctly for Swift?
Please note that all cases works as expected on Android with no crash.
CodePudding user response:
When you call getPokemon()
, all you're doing is creating the flow. The code inside the flow doesn't get executed until later, when you collect the flow.
You can actually remove the @Throws
annotation from getPokemon()
, as that method itself won't throw the exception. You should instead add the annotation to any method where you collect items from the flow.