Skip to content

Instantly share code, notes, and snippets.

@toefel18
Created April 9, 2025 20:42
Show Gist options
  • Select an option

  • Save toefel18/dfe6e58f50e60b26c2871544445b0d5d to your computer and use it in GitHub Desktop.

Select an option

Save toefel18/dfe6e58f50e60b26c2871544445b0d5d to your computer and use it in GitHub Desktop.
RetrofitResponse
package net.utils.retrofit
import retrofit2.Response
/**
* Simple helper class to handle retrofit responses in a readable way for cases like when we need access to the error body
* or specific response status codes.
*/
class RetrofitResponse<T>(val response: Response<T>?, val exception: Throwable?) {
// because the error body can only be read once from the response (because it is a stream), we save it as a lazy that is initialized once
private val errorBody: Lazy<String?> = lazy { runCatching { response?.errorBody()?.string() }.getOrNull() }
/** Returns true when no exception was thrown and retrofit also indicates success */
val isSuccessful: Boolean get() = (!hasException && response?.isSuccessful == true)
/** If an exception was thrown, for example in case of Network IO errors, returns true */
val hasException: Boolean get() = exception != null
/** Returns the response code, or null if no response was returned */
val code: Int? = response?.code()
/** Returns the response body as the unmarshalled type if one was returned*/
val body: T? get() = response?.body()
/** If the response was not successful, returns the error body as a string or null if none available.
* Can be called multiple times, only reads the error body once.
*/
val errorBodySafe: String? get() = errorBody.value
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment