kotlinktorkotlin-multiplatform

Handling Exception in HttpClient Ktor


I have written a common code in a common module as below and tested in JS environment

val response = client.post<HttpResponse>(url) {
    body = TextContent("""{"a":1,"b":2}""", ContentType.Application.Json)
}
if (response.status != HttpStatusCode.OK) {
    logger.error("Error, this one failed bad?")
}

But my code ends at client.post with a canceled corutineException on no network. How do I handle this and any other exception? If there is an internet connection. Nothing fails, I want to be able to handle the exceptions. How?

Note: try, catch doesn't work


Solution

  • well after asking here and there, I got help from github issues and came to this work arround

    try {
        val response = client.post<HttpResponse>(url) {
            body = TextContent("""{"a":1,"b":2}""", ContentType.Application.Json)
        }
        if (response.status != HttpStatusCode.OK) {
            logger.error("Error, this one failed bad?")
        }
    } catch (cause: Throwable) {
        logger.error("Catch your error here")
    }
    

    don't confuse to catch (c: Throwable) with catch (e: Exception)

    hope this helps