Nino
10/07/2022, 10:21 AMCancellationException
).
Wouldn't using a big catch (exception: Exception)
around a suspending function api.getFooResponse()
defeat this purpose and prevent any coroutine calling getFoo()
to be cancelled correctly ? Wouldn't the CancellationException
be "swallowed" ? Should we re-throw it ?
suspend fun getFoo(): Foo? = try {
val fooResponse = api.getFooResponse()
Foo(bar = fooResponse.bar)
} catch (exception: Exception) {
exception.printStackTrace()
null
}
Sam
10/07/2022, 10:25 AMCancellationException
you should stop what you’re doing. You don’t necessarily need to rethrow the exception. The coroutine will still remember that it has been cancelled, and will prevent you from suspending again. But rethrowing it is a good way to make sure that everything exits quickly and doesn’t start trying to do more work.ephemient
10/07/2022, 10:41 AMfinally
block, which runs even if the exception was CancellationException
, whether it was caught or not)Sam
10/07/2022, 10:57 AMgetFoo
turns out to be in a loop, e.g.
while (foo == null) foo = getFoo()
😬 in that case definitely rethrow the exception 😄Nino
10/07/2022, 1:33 PMFlow.catch {}
tho), so I guess I would have to write my own ?
1
fun Throwable.rethrowCancellationOrNull(): Nothing? = if (this is CancellationException) {
throw this
} else {
null
}
Example :
suspend fun getFoo(): Foo? = try {
val fooResponse = api.getFooResponse()
Foo(bar = fooResponse.bar)
} catch (exception: Exception) {
exception.printStackTrace()
exception.rethrowCancellationOrNull()
}
2
suspend fun <T, R> T.runCatchingSuspendOrNull(block: suspend T.() -> R): R? {
return try {
block()
} catch (e: Throwable) {
e.printStackTrace()
if (e is CancellationException) {
throw e
}
null
}
}
Example :
suspend fun getFoo(): Foo? = runCatchingSuspendOrNull {
val fooResponse = api.getFooResponse()
Foo(bar = fooResponse.bar)
}
What do you think ?Sam
10/07/2022, 1:47 PMException
or Throwable
at all. But if you really have to do that, both of those options seem like good chociesNino
10/07/2022, 1:51 PMgetFooResponse()
could throw... but I have no idea what exception could be thrown, and maybe tomorrow a library update would silently add a new thrown exception type, and neither I nor the compiler would know about it. I really hate Exceptions in Kotlin, I really wish everything would be sealed classes instead. ^^Lukasz Kalnik
10/10/2022, 11:10 AM