Skip to content

Instantly share code, notes, and snippets.

@DiegoNovati
Created November 24, 2022 22:41
Show Gist options
  • Save DiegoNovati/970e10cf26b093e89991be8a6468c424 to your computer and use it in GitHub Desktop.
Save DiegoNovati/970e10cf26b093e89991be8a6468c424 to your computer and use it in GitHub Desktop.
Error management using the Either monad
// 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