main.name.remal.gradle_plugins.utils.retrofit2.Call.kt Maven / Gradle / Ivy
package name.remal.gradle_plugins.utils
import retrofit2.Call
import retrofit2.Response
fun Call.fetchResponse(): Response {
val response = execute()
if (response.isSuccessful) {
return response
}
throw createCallException(response)
}
fun Call.fetchNullableBody(): T? {
val response = execute()
if (response.isSuccessful) {
return response.body()
}
throw createCallException(response)
}
fun Call.send() {
val response = execute()
if (!response.isSuccessful) {
throw createCallException(response)
}
}
fun Call.fetchBody(): T {
val response = fetchResponse()
return response.body()
?: throw RetrofitCallException(
response.code(),
buildString {
append("Request ")
request().let {
append(it.method())
append(" ")
append(it.url())
}
append(" have NULL body")
}
)
}
private val mimeTypesToLogBody = setOf("text/plain", "application/json")
fun Call<*>.createCallException(response: Response<*>) = RetrofitCallException(
response.code(),
buildString {
append("Error requesting ")
request().let {
append(it.method())
append(" ")
append(it.url())
}
append(": ")
append(response.code())
append(" ")
append(response.message())
response.errorBody()?.let forBody@{
if (0L == it.contentLength()) return@forBody
append(":\n")
append(it.string())
}
}
)
class RetrofitCallException(val status: Int, message: String) : RuntimeException(message)
© 2015 - 2024 Weber Informatics LLC | Privacy Policy