Skip to content

Instantly share code, notes, and snippets.

@GregKluska
Created November 7, 2020 17:04
Show Gist options
  • Select an option

  • Save GregKluska/096ebb7cc5a1844f52918f272615a8bf to your computer and use it in GitHub Desktop.

Select an option

Save GregKluska/096ebb7cc5a1844f52918f272615a8bf to your computer and use it in GitHub Desktop.
package com.codingwithmitch.cleannotes.business.data.util
import com.codingwithmitch.cleannotes.business.data.cache.CacheConstants.CACHE_TIMEOUT
import com.codingwithmitch.cleannotes.business.data.cache.CacheErrors.CACHE_ERROR_TIMEOUT
import com.codingwithmitch.cleannotes.business.data.cache.CacheErrors.CACHE_ERROR_UNKNOWN
import com.codingwithmitch.cleannotes.business.data.cache.CacheResult
import com.codingwithmitch.cleannotes.business.data.network.ApiResult
import com.codingwithmitch.cleannotes.business.data.network.NetworkConstants.NETWORK_TIMEOUT
import com.codingwithmitch.cleannotes.business.data.network.NetworkErrors.NETWORK_ERROR_TIMEOUT
import com.codingwithmitch.cleannotes.business.data.network.NetworkErrors.NETWORK_ERROR_UNKNOWN
import com.codingwithmitch.cleannotes.business.data.util.GenericErrors.ERROR_UNKNOWN
import kotlinx.coroutines.*
import retrofit2.HttpException
import java.io.IOException
/**
* Reference: https://medium.com/@douglas.iacovelli/how-to-handle-errors-with-retrofit-and-coroutines-33e7492a912
*/
suspend fun <T> safeApiCall(
dispatcher: CoroutineDispatcher,
apiCall: suspend () -> T?
): ApiResult<T?> {
return withContext(dispatcher) {
try {
// throws TimeoutCancellationException
withTimeout(NETWORK_TIMEOUT){
ApiResult.Success(apiCall.invoke())
}
} catch (throwable: Throwable) {
throwable.printStackTrace()
when (throwable) {
is TimeoutCancellationException -> {
val code = 408 // timeout error code
ApiResult.GenericError(code, NETWORK_ERROR_TIMEOUT)
}
is IOException -> {
ApiResult.NetworkError
}
is HttpException -> {
val code = throwable.code()
val errorResponse = convertErrorBody(throwable)
ApiResult.GenericError(
code,
errorResponse
)
}
else -> {
ApiResult.GenericError(
null,
NETWORK_ERROR_UNKNOWN
)
}
}
}
}
}
suspend fun <T> safeCacheCall(
dispatcher: CoroutineDispatcher,
cacheCall: suspend () -> T?
): CacheResult<T?> {
return withContext(dispatcher) {
try {
// throws TimeoutCancellationException
withTimeout(CACHE_TIMEOUT){
CacheResult.Success(cacheCall.invoke())
}
} catch (throwable: Throwable) {
throwable.printStackTrace()
when (throwable) {
is TimeoutCancellationException -> {
CacheResult.GenericError(CACHE_ERROR_TIMEOUT)
}
else -> {
CacheResult.GenericError(CACHE_ERROR_UNKNOWN)
}
}
}
}
}
private fun convertErrorBody(throwable: HttpException): String? {
return try {
throwable.response()?.errorBody()?.string()
} catch (exception: Exception) {
ERROR_UNKNOWN
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment