Which one do you prefer? :one: ```suspend fun <...
# codingconventions
g
Which one do you prefer? 1️⃣
Copy code
suspend 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️⃣
Copy code
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)
    }
}
2️⃣ 3
1️⃣ 9
l
I'd probably go for an alternate route on creating the Resource.Error;
Copy code
catch (e: Exception) { 
  return Resource.Error(e)
}
and handle the exception type inside Resource.Error()
Copy code
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 testing
gratitude thank you 1
very nice 2
👍 1
g
something like this, right?
Copy code
suspend 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
    }
}
👍 3
r
Be very careful here - Exceptions are internally used for coroutine cancellation and catching these will break things in surprising and confusing ways. If you really need to catch all exceptions, make sure you read this first: https://betterprogramming.pub/the-silent-killer-thats-crashing-your-coroutines-9171d1e8f79b
gratitude thank you 3
plus one 2