Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Catching CancellationException in coroutines #38

Open
LeafyLappa opened this issue Jul 4, 2024 · 1 comment
Open

Catching CancellationException in coroutines #38

LeafyLappa opened this issue Jul 4, 2024 · 1 comment

Comments

@LeafyLappa
Copy link

Description

I believe the implementation of error handling in coroutines could be improved by not catching all possible exceptions.

For example, in CharacterDetailViewModel there's this function:

    /**
     * Fetch selected character detail info.
     *
     * @param characterId Character identifier.
     */
    fun loadCharacterDetail(characterId: Long) {
        _state.postValue(CharacterDetailViewState.Loading)
        viewModelScope.launch {
            try {
                val result = marvelRepository.getCharacter(characterId)
                _data.postValue(characterDetailMapper.map(result))

                characterFavoriteRepository.getCharacterFavorite(characterId)?.let {
                    _state.postValue(CharacterDetailViewState.AlreadyAddedToFavorite)
                } ?: run {
                    _state.postValue(CharacterDetailViewState.AddToFavorite)
                }
            } catch (e: Exception) {
                _state.postValue(CharacterDetailViewState.Error)
            }
        }
    }

Here you could theoretically break the normal coroutine cancellation flow. If the coroutine here is cancelled for any reason then the app might show an error even when there's none.

By the way I've seen this kind of problem way too many times in actual production code. What's worse is that people won't even know how to properly fix it.

I generally use the solution I found here: https://betterprogramming.pub/the-silent-killer-thats-crashing-your-coroutines-9171d1e8f79b I find it very simple and nice as it could be used with runCatching...

@1145906886
Copy link

1145906886 commented Jul 4, 2024 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants