Created
June 14, 2023 09:30
-
-
Save Aldikitta/4e50f31f6ad5b06c65ba5148a111f80b to your computer and use it in GitHub Desktop.
This file contains 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
suspend fun <T> asSallyResponseResourceSuspend(apiCall: suspend () -> T): SallyResponseResource<T> { | |
return try { | |
SallyResponseResource.Loading(true) | |
val response = apiCall.invoke() | |
SallyResponseResource.Success(response) | |
} catch (error: Throwable) { | |
val exception = when (error) { | |
is HttpException -> { | |
when (error.code()) { | |
in 400..499 -> { | |
ClientException( | |
message = "${Constant.CLIENT_ERROR}: ${error.code()}", | |
cause = error, | |
) | |
} | |
in 500..599 -> ServerException( | |
message = "${Constant.SERVER_ERROR}: ${error.code()}", | |
cause = error | |
) | |
else -> UnknownException( | |
message = "${Constant.HTTP_UNKNOWN_ERROR}: ${error.code()}", | |
cause = error | |
) | |
} | |
} | |
is IOException -> NetworkException( | |
message = Constant.NETWORK_ERROR, | |
cause = error | |
) | |
else -> AppException( | |
message = Constant.UNKNOWN_ERROR, | |
cause = error | |
) | |
} | |
val errorCode = when (error) { | |
is HttpException -> { | |
when (error.code()) { | |
in 400..499 -> { | |
"#ER${error.code()}" | |
} | |
in 500..599 -> { | |
"#ER${error.code()}" | |
} | |
else -> { | |
"#ER${error.code()}" | |
} | |
} | |
} | |
else -> { | |
error.cause?.message.toString() | |
} | |
} | |
SallyResponseResource.Error(exception, errorCode) | |
} finally { | |
SallyResponseResource.Loading(false) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment