I am building an app and after a response from the backend, I need to extract the body of the http response but I cannot find a good way to do it. The response has an error code 400 and when this happen, I need to extract the body to checkout the specific response.
withContext(Dispatchers.IO) {
when(val response = api.create(id = id, type = type)) {
is CanooResult.Success -> {
Result.Success(it.status)
}
is Result.Error -> {
Result.Error(throwable = response.error, data = handleServerError(response.error))
}
else -> Result.Error(throwable = Throwable("Unknown error"))
}
}
In my case I reach is Result.Error ->
which is exepected but I cannot properly implement handleServerError
the code is as below:
private fun handleServerError(error: Throwable?): String {
val exception = error as? HttpException
val errorBody = exception?.response()?.errorBody()?.string()
//val err = error as HttpException
val bodyJson = Gson().fromJson(
errorBody,ServerError::class.java
)
return when (bodyJson.errorCode) {
ERR_TYPE -> ERR_GENERIC
ERR_DUP -> ERR_DUPLICATE_PROD
else -> UNKNOWN_ERROR
}
}
And the ServerError
class is as below:
data class ServerError(
val message: String,
val errorCode: Int,
)
below is an image of the response I grab using AS.
Any idea what is the issue ?