Are there any coroutines-friendly error handling f...
# coroutines
m
Are there any coroutines-friendly error handling functions? For example, some
runCatching
that doesn't catch
CancellationException
? Would be nice to have some standardized solution (and IDE warnings on catching the
CancellationException
in coroutines)
2
I've tried making my version of
runCatching
but it can't return
kotlin.Result
because it's inline class 😞
l
It's because kotlin.Result might change in the future, so the ABI of the inline class is not exposed to allow changes without breaking people with binary compatibility for JVM users that use libraries compiled before the changes.
m
I assumed so
l
Why do you want to use
kotlin.Result
specifically?
m
I wanted to write version of
runCatching
that won't catch
CancellationException
. Ideally, it would be a simple update to codebase, ideally returning same type
I guess I can make my own Result with same api as
kotlin.Result
g
You can add compiler flag to allow use Result as return type
m
That's probably very unsafe for libraries 😄
g
Yeah, for libraries it's not good, it would require consumer to use this flag too
l
And would more importantly break after they decide to change the ABI of
kotlin.Result
, even with the flag activated (unless they add a mechanism to prevent compilation of such things, which is still breaking things and delaying update until library updates)
m
Am I on the right track here, does this makes sense?
Copy code
public inline fun <R> coRunCatching(block: () -> R): Result<R> {
    return try {
        Result.success(block())
    } catch (e: CancellationException){
        throw e
    } catch (e: Throwable) {
        Result.failure(e)
    }
}
l
LGTM. You're using your own
Result
, right?
m
Haven't coded it yet, but yes.
l
You mean you haven't copy pasted it yet? 😉 (that said, might be a little easier to roll your own simplified version actually)
g
What is your use case for own result?
I mean if it's library maybe domain specific sealed class would be better solution than generic version that just returns some value or exception
m
Use case is that I'd use it instead of
kotlin.Result
, so that updating current code to
coRunCatching
is just changing name of fun called.
l
You can also name it
cancellableRunCatching
, which IMHO is more accurate and makes it more obvious why it's used in place of stdlib's
runCatching
without having to look at the source of the function (which is impractical if not viewed from an IDE with checked out revision, like on VCS UIs or in-IDE diffs).