Skip to content

Instantly share code, notes, and snippets.

@IkemNwodo
Last active January 17, 2022 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save IkemNwodo/0d6319e66b11a10c5aa431ce05a7f062 to your computer and use it in GitHub Desktop.
Save IkemNwodo/0d6319e66b11a10c5aa431ce05a7f062 to your computer and use it in GitHub Desktop.
internal sealed class RepositoryResponse<out T> {
class Success<out T>(val data: T) : RepositoryResponse<T>()
class Error(val error: String) : RepositoryResponse<Nothing>()
class ApiError(val error: ApiError) :
RepositoryResponse<Nothing>()
}
@Serializable
internal data class ApiError(
val statusCode: Int,
val message: String
){
override fun toString(): String {
return when(message){
"SYSTEM FAILURE" -> "Theres's a system failure. Please try later"
else -> message
}
}
}
// Wrap your response object with Response<>
suspend fun scanBarCode(
@HeaderMap headers: Map<String, String>,
@Body request: ScanBarCodeRequest
): Response<ScanBarCodeResponse>
// Then in your repository, call isSuccessful on the response from your api response
// You can also wrap this in a try-catch to cater for other errors
if (result.isSuccessful) {
Timber.d("Repository data: ${result.body()}")
RepositoryResponse.Success(result.body() as ScanBarCodeResponse)
} else {
val apiError = Json.decodeFromString<ApiError>(
(result.errorBody()?.source()?.buffer?.snapshot()?.utf8().toString())
)
Timber.d("Repository error data: $apiError")
RepositoryResponse.ApiError(apiError)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment