How to iterate over HTTP response code in Kotlin

Viewed 21

I am using import java.net.http.HttpClient and my code is as follows:

try {
val response = httpClient.send(httpRequest, BodyHandlers.ofString())
...
when (response.statusCode()) {
                200 -> {
                    result = decodedResponse
                } else -> {
                    val errorResponse = Json.decodeFromString<ErrorObject>(response.body())
                    throw handleCustomError(errorResponse.error, errorResponse.error_description)
                }
            }
return result
} catch (ex: Exception) {
   
            throw Exception("Service is unavailable!")
        }

my handleCustomError iterates over the different types of status codes 401,403,404 etc and throws user friendly exception. But I dont think that code is ever reached. Instead I see the generic exception thrown by the catch block.

How can I make sure to iterate over the different status code?

0 Answers
Related