我将带有协程的Retrofit 2.6.0用于我的Web服务调用。我正在使用所有响应代码(成功和错误情况)正确获取API响应。我的问题是,当我断开API调用之间的互联网(Wifi /移动数据)与我编写的代码的连接时,无法正确捕获错误。大多数时候,错误是ConnectException和SocketException。
我尝试使用拦截器以及从启动了我的调用的ViewModel中捕获错误。但是在这里,也不会捕获和处理异常。
//ApiService
@GET(ApiUrl.API_DASHBOARD)
suspend fun getHomeUiDetails(@Header("Authorization") authHeader: String): Response<HomeDetailsResponse>
//ConnectionBridge
suspend fun getHomeUiDetails(authToken: String): Response<HomeDetailsResponse> {
return ApiServiceGenerator.BASIC_CLIENT_CONTRACT.getHomeUiDetails(authToken)
}
// ViewModel
viewModelScope.launch(Dispatchers.IO) {
val apiResponse = ApiConnectionBridge.getHomeUiDetails(SharedPrefUtils.getAuthToken(context))
if (apiResponse.isSuccessful) {
// success case
} else {
// error case
}
}
object ApiServiceGenerator {
val BASIC_CLIENT_CONTRACT: ApiService = ApiClient
.getContract(
ApiService::class.java,
true,
BuildConfig.BASE_URL
)
}
object ApiClient {
fun <T> getContract(clazz: Class<T>, isAuth: Boolean, baseUrl: String): T {
return getRetrofitBuilder(baseUrl, getContractBuilder(isAuth)).create(clazz)
}
private fun getRetrofitBuilder(baseUrl: String, builder: OkHttpClient.Builder): Retrofit {
val gson = GsonBuilder().serializeNulls().create()
val loggingInterceptor = HttpLoggingInterceptor()
loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
val okHttpClient = OkHttpClient.Builder()
.addInterceptor { chain ->
val original = chain.request()
// Customize the request
val request = original.newBuilder()
request.header("Content-Type", "application/x-www-form-urlencoded")
var response: Response? = null
try {
response = chain.proceed(request.build())
response.cacheResponse()
// Customize or return the response
response!!
} catch (e: ConnectException) {
Log.e("RETROFIT", "ERROR : " + e.localizedMessage)
chain.proceed(original)
} catch (e: SocketException) {
Log.e("RETROFIT", "ERROR : " + e.localizedMessage)
chain.proceed(original)
} catch (e: IOException) {
Log.e("RETROFIT", "ERROR : " + e.localizedMessage)
chain.proceed(original)
} catch (e: Exception) {
Log.e("RETROFIT", "ERROR : " + e.localizedMessage)
chain.proceed(original)
}
}
// .cache(cache)
.eventListener( object : EventListener() {
override fun callFailed(call: Call, ioe: IOException) {
super.callFailed(call, ioe)
}
})
.addInterceptor(loggingInterceptor)
.readTimeout(60, TimeUnit.SECONDS)
.connectTimeout(60, TimeUnit.SECONDS)
.build()
return Retrofit.Builder()
.baseUrl(baseUrl)
.client(okHttpClient)//getUnsafeOkHttpClient()
.addConverterFactory(GsonConverterFactory.create(gson))
.build()
}
}
堆栈跟踪:
2019-08-02 14:15:12.819 4157-4288/com.my.app E/AndroidRuntime: FATAL EXCEPTION: DefaultDispatcher-worker-3
Process: com.my.app, PID: 4157
java.net.ConnectException: Failed to connect to my_url
at okhttp3.internal.connection.RealConnection.connectSocket(RealConnection.java:248)
at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:166)
at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:257)
at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:135)
at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:114)
at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:126)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.logging.HttpLoggingInterceptor.intercept(HttpLoggingInterceptor.java:213)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at com.my.app.network.ApiClient$getRetrofitBuilder$okHttpClient$1.intercept(ApiClient.kt:50)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:254)
at okhttp3.RealCall$AsyncCall.execute(RealCall.java:200)
at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)
Caused by: java.net.ConnectException: failed to connect to my_url (port 80) from /:: (port 0) after 60000ms: connect failed: ENETUNREACH (Network is unreachable)
at libcore.io.IoBridge.connect(IoBridge.java:137)
at java.net.PlainSocketImpl.socketConnect(PlainSocketImpl.java:137)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:390)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:230)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:212)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:436)
at java.net.Socket.connect(Socket.java:621)
at okhttp3.internal.platform.AndroidPlatform.connectSocket(AndroidPlatform.java:73)
at okhttp3.internal.connection.RealConnection.connectSocket(RealConnection.java:246)
at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:166)
at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:257)
at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:135)
at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:114)
at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:126)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.logging.HttpLoggingInterceptor.intercept(HttpLoggingInterceptor.java:213)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at com.my.app.network.ApiClient$getRetrofitBuilder$okHttpClient$1.intercept(ApiClient.kt:50)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:254)
at okhttp3.RealCall$AsyncCall.execute(RealCall.java:200)
at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)
Caused by: android.system.ErrnoException: connect failed: ENETUNREACH (Network is unreachable)
at libcore.io.Linux.connect(Native Method)
at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:118)
at libcore.io.IoBridge.connectErrno(IoBridge.java:168)
at libcore.io.IoBridge.connect(IoBridge.java:129)
at java.net.PlainSocketImpl.socketConnect(PlainSocketImpl.java:137)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:390)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:230)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:212)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:436)
at java.net.Socket.connect(Socket.java:621)
at okhttp3.internal.platform.AndroidPlatform.connectSocket(AndroidPlatform.java:73)
at okhttp3.internal.connection.RealConnection.connectSocket(RealConnection.java:246)
at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:166)
at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:257)
at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:135)
at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:114)
at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:126)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.logging.HttpLoggingInterceptor.intercept(HttpLoggingInterceptor.java:213)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at com.my.app.network.ApiClient$getRetrofitBuilder$okHttpClient$1.intercept(ApiClient.kt:50)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:254)
at okhttp3.RealCall$AsyncCall.execute(RealCall.java:200)
at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)
答案 0 :(得分:5)
好吧,我就是这样做的,只是为了减少尝试捕获的垃圾复制粘贴
声明这样的API调用方法
@GET("do/smth")
suspend fun doSomething(): SomeCustomResponse
在单独的文件中
suspend fun <T: Any> handleRequest(requestFunc: suspend () -> T): kotlin.Result<T> {
return try {
Result.success(requestFunc.invoke())
} catch (he: HttpException) {
Result.failure(he)
}
}
用法:
suspend fun doSmth(): kotlin.Result<SomeCustomResponse> {
return handleRequest { myApi.doSomething() }
}
HTTP代码由Retrofit处理-如果responseCode不是2xx,它只会抛出HttpException。因此,我们应该做的就是捕获此异常。
我知道,这不是一个完美的解决方案,但是让杰克发明更好的东西
答案 1 :(得分:1)
我参加聚会有点晚了,但是我认为这是最好的解决方法:
如果您使用的是 Kotlin + Retrofit + Coroutines ,则只需对网络操作使用try
和catch
viewModelScope.launch(Dispatchers.IO) {
try {
val userListResponseModel = apiEndPointsInterface.usersList()
returnusersList(userListResponseModel)
} catch (e: Exception) {
e.printStackTrace()
}
}
其中,异常是kotlin
而不是java.lang
这将处理所有类似的异常,
这是我的usersList()
函数
@GET(AppConstants.APIEndPoints.HOME_CONTENT)
suspend fun usersList(): UserListResponseModel
注意:
您的RetrofitClient类必须具有client
OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
答案 2 :(得分:0)
此问题不需要拦截器。像这样用try / catch包装改造API调用:
suspend fun getHomeUiDetails(authToken: String): Response<HomeDetailsResponse>
return try {
val response = yourRetrofitService.getHomeUiDetails(authToken)
if (response.isSuccessful) {
return response
}
return Result.Error(
IOException("Error getting details ${response.code()} ${response.message()}")
)
} catch (e: Exception) {
Result.Error(IOException("Error getting details", e))
}
}
答案 3 :(得分:0)
也许它可以帮助某人:
可以通过以下方式摆脱SocketTimeoutException
:
1.将客户端的readTimeout设置为任意数字,此处为2s
val client = OkHttpClient.Builder()
.connectTimeout(1, TimeUnit.SECONDS)
.readTimeout(2, TimeUnit.SECONDS).build()
2。进行API调用时,请始终将它们包装在协程超时内。
try {
withTimeout(1000) {
try {
val retrivedTodo = APICall()
emit(retrivedTodo)
} catch (exception: HttpException) {
exception.printStackTrace()
}
}
}catch (ex: CancellationException) {
Log.e("timeout","TimeOut")
}
主要要点是 withTimeout 值小于Retrofit timeout值。这样可以确保协程在暂停改装超时之前停止挂起。
无论如何,这会产生许多try / catch块,而当包含协程支持时,可能不是改造开发人员想要的。
答案 4 :(得分:0)
您只需添加CoroutineExceptionHandler
即可为您处理错误:
在您的ViewModel中:
val coroutineExceptionHandler = CoroutineExceptionHandler{_, t -> {
t.printStackTrace()
showErrorOrSomething()
}}
viewModelScope.launch(Dispatchers.IO + coroutineExceptionHandler) {
val apiResponse = ApiConnectionBridge.getHomeUiDetails(SharedPrefUtils.getAuthToken(context))
if (apiResponse.isSuccessful) {
// success case
} else {
// error case
}
}
答案 5 :(得分:0)
Arthur Matsegor的回答的补充:
在我的情况下,API向我返回错误消息,提示错误的请求。对于这种情况,我需要在Catch函数上捕获错误消息。我知道,将try / catch编写为Catch函数看起来很丑,但确实可行。
private suspend fun <T : Any> handleRequest(requestFunc: suspend () -> T): Result<T> {
return try {
Result.success(requestFunc.invoke())
} catch (httpException: HttpException) {
val errorMessage = getErrorMessageFromGenericResponse(httpException)
if (errorMessage.isNullOrBlank()) {
Result.failure(httpException)
} else {
Result.failure(Throwable(errorMessage))
}
}
}
private fun getErrorMessageFromGenericResponse(httpException: HttpException): String? {
var errorMessage: String? = null
try {
val body = httpException.response()?.errorBody()
val adapter = Gson().getAdapter(GenericResponse::class.java)
val errorParser = adapter.fromJson(body?.string())
errorMessage = errorParser.errorMessage?.get(0)
} catch (e: IOException) {
e.printStackTrace()
} finally {
return errorMessage
}
}
答案 6 :(得分:0)
您可以在ViewModel中执行以下操作以优雅地处理异常:
viewModelScope.launch {
kotlin.runCatching {
withContext(Dispatchers.IO){
ApiConnectionBridge.getHomeUiDetails(SharedPrefUtils.getAuthToken(context))
}
}.onSuccess {
// do something with success response
}.onFailure{
// do something on failure response
}
}