Skip to content

Instantly share code, notes, and snippets.

@virtual-addy
Created October 12, 2021 12:02
Show Gist options
  • Save virtual-addy/34c08ec9dd4351c1fa0dfa0a2287dd2d to your computer and use it in GitHub Desktop.
Save virtual-addy/34c08ec9dd4351c1fa0dfa0a2287dd2d to your computer and use it in GitHub Desktop.
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