Created
October 12, 2021 12:02
-
-
Save virtual-addy/34c08ec9dd4351c1fa0dfa0a2287dd2d to your computer and use it in GitHub Desktop.
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
suspend fun <T : Any> makeRequestToApi( | |
call: suspend () -> T, | |
): ApiResult<T> { | |
return try { | |
val data = call.invoke() | |
ApiResult.Success(data) | |
} catch (throwable: Exception) { | |
return when (throwable) { | |
is HttpException -> { | |
ApiResult.HttpError(throwable.code(), parseErrorMessage(throwable)) | |
} | |
is IOException -> ApiResult.NoInternet | |
else -> ApiResult.GenericError(throwable) | |
} | |
} | |
} | |
fun parseErrorMessage(httpException: HttpException): String { | |
val errorBody = httpException.response()?.errorBody()?.string() | |
return try { | |
val messageObject = Gson().fromJson(errorBody, JsonObject::class.java) | |
messageObject.get("message").asString | |
} catch (ex: Exception) { | |
"" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment