Use of runCatching and coroutines breaks structured concurrency
See original GitHub issueSince runCatching catches all exceptions, it catches CancellationException which prevents any coroutines launched within the runCatching block from being cancelled when their enclosing CoroutineScope is cancelled.
This is not, strictly speaking, an issue with kotlin-result but it caught me by surprise so I thought it would probably be good to warn others of the potential gotcha.
I propose:
- A warning in the kdoc comment, pointing out the problem or,
- 1 + a new function in
kotlin-result-coroutinescalled something likerunSuspendCatching()which rethrowsCancellationException.
I’ve already written a version of runSuspendCatching() and a test case that demonstrates the behaviour in my own project so I’m more than happy to submit a PR if you want.
The same issue has been raised for the stdlib runCatching at Kotlin/kotlinx.couroutines#1814 but it doesn’t seem like the Kotlin devs thinks it’s much of a problem. I disagree and thought maybe we could at least improve things here!
Issue Analytics
- State:
- Created 2 years ago
- Comments:6 (3 by maintainers)

Top Related StackOverflow Question
I also think a syntax like
rethrow()<>for the specific result types where Err extends Exception reads better.For cases where result Err is of some other type that does not extend exception, i think it would be difficult to make a more generic version of this function without throwing something, unless perhaps a third state was added to Result, something like
Result.ExcludedErrwhere invoking things like onSuccess and onFailure on it do nothing.@grodin separate PRs for each one would be best.