Kotlin Android Retrofit 2.6.0 with coroutines error handling

后端 未结 7 2039
粉色の甜心
粉色の甜心 2021-01-30 23:09

I am using Retrofit 2.6.0 with coroutines for my web service call. I am getting the API response properly with all response codes (success & error cases). My Issue is when I

7条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-30 23:56

    You don't need interceptors for this problem. Wrap the retrofit API call with try/catch like this:

    suspend fun getHomeUiDetails(authToken: String): Result
            return try {
                val response = yourRetrofitService.getHomeUiDetails(authToken)
    
                if (response.isSuccessful) {
                    return Result.Success(response)
                }
    
                return Result.Error(
                    IOException("Error getting details ${response.code()} ${response.message()}")
                )
            } catch (e: Exception) {
                Result.Error(IOException("Error getting details", e))
            }
    }
    

提交回复
热议问题