Skip to content

Instantly share code, notes, and snippets.

@thomaskioko
Created July 25, 2023 13:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save thomaskioko/29de5dc303182a29b289c6380cb0c1ab to your computer and use it in GitHub Desktop.
Save thomaskioko/29de5dc303182a29b289c6380cb0c1ab to your computer and use it in GitHub Desktop.
suspend inline fun <reified T, reified E> HttpClient.safeRequest(
block: HttpRequestBuilder.() -> Unit,
): ApiResponse<T, E> =
try {
val response = request { block() }
ApiResponse.Success(response.body())
} catch (exception: ClientRequestException) {
ApiResponse.Error.HttpError(
code = exception.response.status.value,
errorBody = exception.response.body(),
errorMessage = "Status Code: ${exception.response.status.value} - API Key Missing",
)
} catch (exception: HttpExceptions) {
ApiResponse.Error.HttpError(
code = exception.response.status.value,
errorBody = exception.response.body(),
errorMessage = exception.message,
)
} catch (e: SerializationException) {
ApiResponse.Error.SerializationError(e.message)
} catch (e: Exception) {
ApiResponse.Error.GenericError(e.message)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment