Search code examples
androidkotlinktor

Ktor ClientRequestException - get server message embedded in the ClientRequestException message


I have a server that is returning a 400 response with an error message like this

{ "message": "Username already exist, please try a different one.", "code": 400 }

and in ktor client I am setting the HTTPClient to expect true like this

 HttpClient {
     expectSuccess = true
 }

but when I try to get the exception it returns a ClientRequestException and the server message is wrapped in ClientRequestException stuff

this is the full message I get when I do exception.message

 Client request(POST http://10.0.2.2:8080/account/signup) invalid: 400 Bad Request. Text: "{ "message": "Username already exist, please try a different one.", "code": 400 }"

any way I can just get the server message from ClientRequestException?


Solution

  • You can access the response property of the ClientRequestException to get the response object. You can then call its body method to receive the deserialized response body as an object: e.response.body<ErrorResponse>(). Please refer to the official documentation to learn about handling responses.