Hello, Is this the correct procedure to catch a 3r...
# ktor
g
Hello, Is this the correct procedure to catch a 3rd party API error, parse it to evaluate the type of exception, and proceed with custom logic? Details in thread 🧵 Thanks!
This is the serverApp, which requests data from a Google API with the Bearer provided by the client. If it get’s 401, redirects it to de client in the HttpStatusCode.Unauthorized format:
Copy code
kotlin.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:
Copy code
} catch (e: ClientRequestException) {
    when(e.response.status) {
        HttpStatusCode.Unauthorized -> throw AuthenticationException()
        else -> call.respond(HttpStatusCode.InternalServerError, "Ups, something went wrong: ${e.message}")
    }
}