Retrofit 2: Catch connection timeout exception

后端 未结 7 1289
执念已碎
执念已碎 2020-11-27 03:26

I have the following setup:

final OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.setReadTimeout(5, TimeUnit.SECONDS);
okHttpClient.setConnectTi         


        
7条回答
  •  悲哀的现实
    2020-11-27 04:24

    Kotlin

    If you want to use Retrofit in Kotlin follow below steps:

    Define your Retrofit interface:

    interface GitHubApi {
    
        @GET("/users/{userName}/repos")
        fun repos(@Path("userName") userName: String): Call>
    }
    

    Implement your service:

    class Api(...) {
    
        private val baseUrl = "https://api.github.com"
        private val api: GitHubApi
    
        private fun loggingInterceptor(...): HttpLoggingInterceptor {...}
    
        private fun okHttpBuilder(): OkHttpClient {...}
    
        init {...}
    
        fun repos(
            userName: String,
            onSuccess: (list: List?) -> Unit,
            onFailure: (message: String?) -> Unit): Future {
            return runAsync(api.repos(userName), onSuccess, onFailure)
        }
    
        private fun  runAsync(
            call: retrofit2.Call,
            onSuccess: (T?) -> Unit,
            onFailure: (message: String?) -> Unit) : Future {
            return doAsync {
                try {
                    val response = call.execute()
                    when {
                        response.isSuccessful -> response.body()?.let {
                            onSuccess(it)
                        }
                        else -> {
                            onFailure(response.raw().message())
                        }
                    }
                } catch (e: IOException) {
                    if (e is SocketTimeoutException) {
                        onFailure("Response time out!")
                    } else {
                        onFailure(e.message)
                    }
                }
            }
        }
    }
    

    Call your service in where you want:

    Api().repos("olcayertas",
        onSuccess = {
            Log.d("MainActivity", "Response:\n" + toJson(it))
        },
        onFailure = {
            Log.e("MainActivity", "Error: $it")
        })
    

    You can handle any exception you want in runAsync function.

    You can get fully working example here.

提交回复
热议问题