[英]Crash OkHttp dispatcher when use kotlin-coroutine
我正在使用 okHttp 加載數據。
加載數據時發生 RuntimeException,導致 okhttpDispatcher 崩潰。
我使用協程,但它們沒有捕獲異常並且應用程序崩潰。
如何正確捕獲攔截器中拋出的異常?
注意:如果發生 IOException,該構造將正常執行。
class CommentsViewModel(val api: IRetrofitApi): ViewModel(){
fun getComments(){
viewModelScope.launch(exceptionHandler) {
api.loadComments() //When RuntimeException this didn`t catch
}
}
val exceptionHandler = CoroutineExceptionHandler { _, throwable ->
showError(throwable)
}
}
interface IRetrofitApi {
@GET("/comments")
suspend fun loadComments() : CommentList
}
class NetworkModule{
fun getClient(): OkHttpClient {
return OkHttpClient.Builder()
.addInterceptor{ chain ->
val request = chain.request().newBuilder()
chain.proceed(request.build())
throw RuntimeException()
}.build()
}
}
見https://stackoverflow.com/a/58711127/1542667
您不應該從攔截器中拋出 RuntimeException,它被視為無法干凈處理的致命錯誤。 OkHttp 偶爾會包裝來自底層庫(如 Android 網絡)的特定 RuntimeExceptions,但否則您應該使用 IOException。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.