George Z
12/31/2024, 5:59 PMsuspend fun <T : Any> handleApi(execute: suspend () -> T): Resource<T> {
return try {
val response = execute()
Resource.Success(response)
} catch (e: Exception) {
Resource.Error(
when (e) {
is IOException -> ErrorType.Network
is HttpException -> mapApiError(e.code())
is SerializationException -> ErrorType.Serialization
else -> ErrorType.Unknown
}
)
}
}
2️⃣
suspend fun <T : Any> handleApi(execute: suspend () -> T): Resource<T> {
return try {
val response = execute()
Resource.Success(response)
} catch (e: IOException) {
Resource.Error(ErrorType.Network)
} catch (e: HttpException) {
Resource.Error(mapApiError(e.code()))
} catch (e: SerializationException) {
Resource.Error(ErrorType.Serialization)
} catch (e: Exception) {
Resource.Error(ErrorType.Unknown)
}
}
LeoColman
12/31/2024, 6:15 PMcatch (e: Exception) {
return Resource.Error(e)
}
and handle the exception type inside Resource.Error()
fun Resource.Error(e: Exception) {
when(e) {
is IOException -> Resource.Error(ErrorTypeNetwork)
}
}
Would take the code to a different place instead of inside a catch block and will help with testingGeorge Z
12/31/2024, 6:26 PMsuspend fun <T : Any> handleApi(execute: suspend () -> T): Resource<T> {
return try {
val response = execute()
Resource.Success(response)
} catch (e: Exception) {
Resource.Error(mapException(e))
}
}
private fun mapException(exception: Exception): ErrorType {
return when (exception) {
is IOException -> ErrorType.Network
is HttpException -> mapApiError(exception.code())
is SerializationException -> ErrorType.Serialization
else -> ErrorType.Unknown
}
}
Robert Williams
01/02/2025, 10:35 AM