Simplify error handling
This commit is contained in:
@@ -0,0 +1,15 @@
|
||||
package gq.kirmanak.mealient.extensions
|
||||
|
||||
import kotlinx.coroutines.CancellationException
|
||||
|
||||
/**
|
||||
* Like [runCatching] but rethrows [CancellationException] to support
|
||||
* cancellation of coroutines.
|
||||
*/
|
||||
inline fun <T> runCatchingExceptCancel(block: () -> T): Result<T> = try {
|
||||
Result.success(block())
|
||||
} catch (e: CancellationException) {
|
||||
throw e
|
||||
} catch (e: Throwable) {
|
||||
Result.failure(e)
|
||||
}
|
||||
@@ -1,8 +1,11 @@
|
||||
package gq.kirmanak.mealient.extensions
|
||||
|
||||
import gq.kirmanak.mealient.data.network.NetworkError
|
||||
import kotlinx.serialization.ExperimentalSerializationApi
|
||||
import kotlinx.serialization.SerializationException
|
||||
import kotlinx.serialization.json.Json
|
||||
import kotlinx.serialization.json.decodeFromStream
|
||||
import retrofit2.HttpException
|
||||
import retrofit2.Response
|
||||
import timber.log.Timber
|
||||
import java.io.InputStream
|
||||
@@ -16,3 +19,7 @@ inline fun <reified T> Json.decodeFromStreamOrNull(stream: InputStream): T? =
|
||||
.onFailure { Timber.e(it, "decodeFromStreamOrNull: can't decode") }
|
||||
.getOrNull()
|
||||
|
||||
fun Throwable.mapToNetworkError(): NetworkError = when (this) {
|
||||
is HttpException, is SerializationException -> NetworkError.NotMealie(this)
|
||||
else -> NetworkError.NoServerConnection(this)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user