Search code examples
kotlinhttpresponsektor

failing to get the response error message in ktor


I'm trying to print the message returned from the post response request, when there is an error. So the message I get in postman, when I do a bad request is:

{"Error": "This email is already in use!"}

Then I get the body() of it as follows:

return kotlin.runCatching {
            val response = client.post {
                url(HttpRoutes)
                contentType(ContentType.Application.Json)
                setBody(postRequest)
            }
                response.body()
        }

The expecting response is as follows:

    @Serializable
data class UserPostResponse (
    @SerialName("Activation")
    val activation: Map<String, String>? = null,
    @SerialName("Error")
    val error: Map<String, String>? = null
)

in my viewModel I launch that service and onFailure(which happens) I want to println(response.message). However, I'm getting the following error:

RESPONSE failed with exception: io.ktor.serialization.JsonConvertException: Illegal input: Unexpected JSON token at offset 9: Expected start of the object '{', but had ' ' instead at path: $.Error

please help!


Solution

  • Instead of waiting

    @Serializable
    data class UserPostResponse (
        @SerialName("Activation")
        val activation: Map<String, String>? = null,
        @SerialName("Error")
        val error: Map<String, String>? = null
    )
    

    change the type from Map string -> String. The Json is already converting it to string