Last active
January 17, 2022 14:03
-
-
Save IkemNwodo/0d6319e66b11a10c5aa431ce05a7f062 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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