Guilherme Delgado
04/29/2021, 12:15 PMGuilherme Delgado
04/29/2021, 12:15 PMkotlin.runCatching {
val response = client.get<SomeApiData>("<https://www.googleapis.com/>...") { ... }
}.getOrElse {
if (it is ClientRequestException) {
var message = it.message ?: "InternalServerError"
val content = it.response.readText(Charset.defaultCharset())
try {
val apiError = Json{ignoreUnknownKeys = true}.decodeFromString<GoogleApiErrorResponse>(content)
when (apiError.error.code) {
HttpStatusCode.Unauthorized.value -> call.respond(HttpStatusCode.Unauthorized)
else -> message = apiError.error.message
}
} catch (ignore: JsonSyntaxException) { }
call.respond(HttpStatusCode.InternalServerError, message)
} else {
call.respond(HttpStatusCode.InternalServerError, it.message ?: "InternalServerError")
}
}
Client:
} catch (e: ClientRequestException) {
when(e.response.status) {
HttpStatusCode.Unauthorized -> throw AuthenticationException()
else -> call.respond(HttpStatusCode.InternalServerError, "Ups, something went wrong: ${e.message}")
}
}