Kotlin Android Retrofit 2.6.0 with coroutines error handling

后端 未结 7 2060
粉色の甜心
粉色の甜心 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:44

    I am a bit late to the party but I think this is the finest solution:

    If you are using Kotlin + Retrofit + Coroutines then just use try and catch for network operations like,

    viewModelScope.launch(Dispatchers.IO) {
            try {
                val userListResponseModel = apiEndPointsInterface.usersList()
                returnusersList(userListResponseModel)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    

    Where, Exception is type of kotlin and not of java.lang

    This will handle every exception like,

    1. HttpException
    2. SocketTimeoutException
    3. FATAL EXCEPTION: DefaultDispatcher etc

    Here is my usersList() function

    @GET(AppConstants.APIEndPoints.HOME_CONTENT)
    suspend fun usersList(): UserListResponseModel
    

    Note: Your RetrofitClient Class must have this as client

    OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
    

提交回复
热议问题