Created
November 24, 2022 22:41
-
-
Save DiegoNovati/970e10cf26b093e89991be8a6468c424 to your computer and use it in GitHub Desktop.
Error management using the Either monad
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This is how to manage the errors returned by a use case using the Either monad | |
fun doLogin() { | |
val params = UseCaseCommonMainLogin.AuthenticationLoginParams( | |
username = localState.data.username, | |
password = localState.data.password, | |
) | |
useCaseCommonMainLogin.invoke(params, viewModelScope) { result -> | |
result.fold(::displayError, ::navigateToHome) // 'result' is of type Either<CommonMainFailure, Unit> | |
} | |
fun displayError(failure: CommonMainFailure) { | |
val errorMessage = when (failure) { | |
CommonMainFailure.ConnectionError -> "There are connection problem: please verify that the Internet connection is working" | |
CommonMainFailure.BackendError -> "The backend seems to experience some problems. Please retry in few minutes" | |
CommonMainFailure.LoginError -> "Login error. Please verify the username and the password" | |
} | |
} | |
sealed interface CommonMainFailure { | |
object ConnectionError : CommonMainFailure | |
object BackendError : CommonMainFailure | |
object LoginError : CommonMainFailure | |
} | |
class UseCaseCommonMainLogin { | |
... | |
suspend fun invoke( | |
params: AuthenticationLoginParams, | |
coroutineScope: CoroutineScope, | |
onResult: (result: Either<CommonMainFailure, Unit>) -> Unit | |
) { | |
... | |
} | |
... | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment