From dc6084ee256c66edfda07ab87d735c2d1f63649f Mon Sep 17 00:00:00 2001 From: Kirill Kamakin Date: Sat, 27 Nov 2021 00:18:56 +0300 Subject: [PATCH] Move auth response handling to runCatching runCatching is easier to read and understand than mapCatching --- .../mealient/data/auth/impl/AuthDataSourceImpl.kt | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/app/src/main/java/gq/kirmanak/mealient/data/auth/impl/AuthDataSourceImpl.kt b/app/src/main/java/gq/kirmanak/mealient/data/auth/impl/AuthDataSourceImpl.kt index 720c9e1..d342ca5 100644 --- a/app/src/main/java/gq/kirmanak/mealient/data/auth/impl/AuthDataSourceImpl.kt +++ b/app/src/main/java/gq/kirmanak/mealient/data/auth/impl/AuthDataSourceImpl.kt @@ -30,17 +30,18 @@ class AuthDataSourceImpl @Inject constructor( val authService = retrofitBuilder.buildRetrofit(baseUrl).create() val accessToken = runCatching { - authService.getToken(username, password) - }.mapCatching { - Timber.d("authenticate() response is $it") - if (!it.isSuccessful) { - val cause = HttpException(it) - throw when (it.decodeErrorBodyOrNull()?.detail) { + val response = authService.getToken(username, password) + Timber.d("authenticate() response is $response") + if (response.isSuccessful) { + checkNotNull(response.body()).accessToken + } else { + val cause = HttpException(response) + val errorDetail: ErrorDetail? = response.decodeErrorBodyOrNull(json) + throw when (errorDetail?.detail) { "Unauthorized" -> Unauthorized(cause) else -> NotMealie(cause) } } - checkNotNull(it.body()).accessToken // Can't be null here, would throw SerializationException }.onFailure { Timber.e(it, "authenticate: getToken failed") throw when (it) {