Skip to content

Instantly share code, notes, and snippets.

@MaxMichel2
Created October 3, 2024 11:12
Show Gist options
  • Save MaxMichel2/a60ba77cd9c0c60f48e15e075fa097be to your computer and use it in GitHub Desktop.
Save MaxMichel2/a60ba77cd9c0c60f48e15e075fa097be to your computer and use it in GitHub Desktop.
suspend fun <D, E> safeApiCall(
apiCall: suspend () -> D,
onError: suspend (StatusCode) -> E? = { null }
): DataResult<D, E> {
return withContext(Dispatchers.IO) {
try {
DataResult.Success(apiCall.invoke())
} catch (e: IOException) {
when (val appError = e.mapToAppError()) {
is AppError.NetworkError -> when (val error = onError(appError.statusCode)) {
null -> throw e
else -> DataResult.Error(error)
}
else -> throw e
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment