简体   繁体   English

使用 kotlin-coroutine 时 OkHttp 调度程序崩溃

[英]Crash OkHttp dispatcher when use kotlin-coroutine

I am loading data using okHttp.我正在使用 okHttp 加载数据。

RuntimeException occurs while loading data, causing the okhttpDispatcher to crash.加载数据时发生 RuntimeException,导致 okhttpDispatcher 崩溃。

I use coroutines, but they do not catch the exception and the application crashes.我使用协程,但它们没有捕获异常并且应用程序崩溃。

How to properly catch the exception thrown in the interceptor?如何正确捕获拦截器中抛出的异常?

Note: In case of an IOException, this construction will be executed normally.注意:如果发生 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()

    }
}

See https://stackoverflow.com/a/58711127/1542667https://stackoverflow.com/a/58711127/1542667

You should not throw RuntimeException from an interceptor, it's treated as a fatal error that isn't possible to handle cleanly.您不应该从拦截器中抛出 RuntimeException,它被视为无法干净处理的致命错误。 OkHttp very occasionally wraps specific RuntimeExceptions from underlying libraries like Android networking, but otherwise you are expected to use IOException. OkHttp 偶尔会包装来自底层库(如 Android 网络)的特定 RuntimeExceptions,但否则您应该使用 IOException。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM