【发布时间】:2019-11-07 19:23:17
【问题描述】:
我在 android kotlin 中使用协程和改造进行 API 调用时遇到致命异常。应用程序崩溃并出现以下异常。
E/AndroidRuntime: FATAL EXCEPTION: DefaultDispatcher-worker-7
Process: com.jamhub.barbeque, PID: 18525
java.net.SocketTimeoutException: timeout
at okhttp3.internal.http2.Http2Stream$StreamTimeout.newTimeoutException(Http2Stream.java:656)
at okhttp3.internal.http2.Http2Stream$StreamTimeout.exitAndThrowIfTimedOut(Http2Stream.java:664)
at okhttp3.internal.http2.Http2Stream.takeHeaders(Http2Stream.java:153)
at okhttp3.internal.http2.Http2Codec.readResponseHeaders(Http2Codec.java:131)
at okhttp3.internal.http.CallServerInterceptor.intercept(CallServerInterceptor.java:88)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:45)
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)
尝试添加超时,CoroutineExceptionHandler
val client = OkHttpClient().newBuilder().addInterceptor(object : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
.newBuilder()
.build()
return chain.proceed(request)
}
}).callTimeout(30, TimeUnit.SECONDS)
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build()
retrofitSocial = Retrofit.Builder()
.baseUrl(BuildConfig.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build()
如果异常发生理想情况下它不应该崩溃它应该返回请求失败。
【问题讨论】:
-
尝试将您的
connectTimeout增加到 30 或更多。 -
我必须处理异常以避免崩溃。所以增加时间可能无助于避免崩溃。
-
你的改造电话是什么样的?你想抓住它吗?
-
@Egor 我有。 val api = InjectorUtils.retrofitInstance?.create(LoginAPI::class.java) CoroutineScope(Dispatchers.IO).launch { val response = api?.generateOTP(otpRequestBody) withContext(Dispatchers.Main) { try { when (response?.代码()) { } } 捕捉(e:HttpException){ } } }
-
This 可能会有所帮助
标签: android kotlin kotlin-coroutines