https://kotlinlang.org logo
#ktor
Title
# ktor
r

Ruben Quadros

11/25/2021, 3:53 PM
Hi, at my ktor client I want to transform the server response to a custom one. I am intercepting
HttpResponsePipeline.Transform
for that. I want to know if we can parse error response from server as well at this point? Any help would be great! Code in thread.
Copy code
client.responsePipeline.intercept(HttpResponsePipeline.Transform) { (info, body) ->
    val response = if (context.response.status == HttpStatusCode.OK) {
            //transform to success response
            SuccessResponse(body)
        } else {
           //read error response body?    
        }
    proceedWith(HttpResponseContainer(info, response))
}

val response: MyCustomResponse = client.get("some url")
I can have a success response as:
Copy code
{
  "name": "NAME",
  "message": "MESSAGE"
}
and error response as:
Copy code
{
  "error": "ERROR",
  "message": "MESSAGE"
}
a

Aleksei Tirman [JB]

11/26/2021, 8:02 AM
You can do it if you disable default response validation by adding
expectSuccess = false
to the client's configuration. Also,
SuccessResponse
and
ErrorResponse
should implement the same interface
MyCustomResponse
.
👍 1
2 Views